众所周知,我们可以创建整数,浮点数,双精度数等数组。类似地,我们可以创建对象数组。
通过使用此对象数组,我们可以访问每个对象(它们是该数组的元素)的类方法。
考虑示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Student
{
//私有数据成员
private int rollno ;
private string name ;
private int age ;
//设置学生详细信息的方法
public void SetInfo(string name, int rollno, int age)
{
this.rollno = rollno ;
this.age = age;
this.name = name;
}
//打印学生详细信息的方法
public void printInfo()
{
Console.WriteLine("Student Record: ");
Console.WriteLine("\tName : " + name );
Console.WriteLine("\tRollNo : " + rollno);
Console.WriteLine("\tAge : " + age );
}
}
class Program
{
static void Main()
{
//创建对象数组
Student[] S = new Student[2];
//由detauls / internal构造函数初始化对象
S[0] = new Student();
S[1] = new Student();
//读取并打印第一个对象
S[0].SetInfo("Herry", 101, 25);
S[0].printInfo();
//读取并打印第二个对象
S[1].SetInfo("Potter", 102, 27);
S[1].printInfo();
}
}
}输出结果
Student Record: Name : Herry RollNo : 101 Age : 25 Student Record: Name : Potter RollNo : 102 Age : 27
在这里,我们为学生创建了一个类,并创建了对象数组来读取,打印学生的详细信息。