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

我们已经在C#.Net中讨论了参数化构造函数和对象数组,在此示例中,我们同时使用了对象数组和参数化构造函数这两个概念。在这里,类的数据成员将通过构造函数进行初始化。

考虑示例:

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 Student(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   );
		}

	}

	//类,包含main方法
	class Program
	{
		//主要方法
		static void Main()
		{
			//对象数组
			Student[] S = new Student[2];
			//在这里,默认构造函数将被调用
			S[0] = new Student();
			//在这里,参数化的构造函数将被调用
			S[1] = new Student("Potter", 102, 27);
			
			//打印两个对象
			S[0].printInfo();
			S[1].printInfo();
		}
	}
}

输出结果

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

在此,将通过默认构造函数初始化S [0]对象的数据成员,并通过参数化构造函数初始化S [1]对象的数据成员。