如何使用C#中的对象数组调用默认构造函数?

在上一篇文章中,我们讨论了C#中的对象数组。在这里,我们将学习如何创建/设计默认构造函数以及如何使用对象(由对象数组创建)访问/调用它们。

考虑示例:

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 Student()
		{
			rollno = 100;
			name   = "Harmaini";
			age    = 16;
		}
		
		//设置学生详细信息的方法
		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];
			//使用默认构造函数进行对象初始化
			S[0] = new Student();
			S[1] = new Student();
			//打印第一个对象
			S[0].printInfo();
			//在第二个对象中设置不同的值
			S[1].SetInfo("Potter", 102, 27);
			//打印第二个对象
			S[1].printInfo();
		}
	}
}

输出结果

Student Record:
        Name     : Harmaini
        RollNo   : 100
        Age      : 16
Student Record:
        Name     : Potter
        RollNo   : 102
        Age      : 27

在此程序中,对象S [0]和S [1]的数组有两个元素,当创建对象时,它们都将调用默认构造函数。

对于第二个对象S [1],我们正在调用setInfo()将替换通过默认构造函数分配的默认值的方法。