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  = 101       ;
			name    = "Herry"   ;
			age     = 12;
		}

		//参数化构造函数 
		public Student(string name, int rollno, int age) 
		{
			//用传递的参数初始化数据成员 
			this.rollno = rollno  ;
			this.age  = age;
			this.name = name;
		}		

		//设置值的方法 
		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 S1 = new Student();
			//打印通过初始化的值 
			//默认构造函数 
			S1.printInfo();

			//创建另一个对象 
			Student S2 = new Student("George", 102, 13);
			//打印由参数化构造函数定义的值
			S2.printInfo();
		}
	}
}

输出结果

Student Record:
        Name     : Herry
        RollNo   : 101
        Age      : 12
Student Record:
        Name     : George
        RollNo   : 102
        Age      : 13

这里,对象S1的成员将通过默认构造函数进行初始化,默认值为:

Name : "Herry"
RollNo: 101
Age : 12

并且,对象S2的成员将通过参数化构造函数进行初始化,默认值为:

Name : "George"
RollNo: 102
Age : 13