使用构造方法能解决:
1)在赋初值的时候重复的书写对象名
2) 假如我们有一个属性,不允许用户随意改动,我们一般把这个属性定义为只读类型的属性,那么这个只读类型的属性就不能再实例化后对他赋值,那么我们对他初始化呢?我们可以通过构造方法来进行初始化。
注意:
我们定义好一个类,如果没有写构造方法,那么编译器就会自动在这个类中给我们添加一个没有参数的构造方法。
一旦我们写了一个构造方法,那么编译器就不会再给我们添加这个没有参数构造方法了。
构造函数实例:
Student中定义: 命名
public class Student
{
public Student(string name, int age, char gender, int chinese, int math, int english)
{
this._name = name;
this._age = age;
this._gender = gender;
this._chinese = chinese;
this._math = math;
this._english = english;
}
public Student(string name, char gender)
{
this._name=name;
this._gender = gender;
}
----------
string _name;
public string name
{
get { return _name; }
}
int _age = 18;
public int Age
{
get { return _age; }
}
char _gender;
public char Gender
{
get { return _gender; }
}
int _chinese;
public int Chinese
{
get { return _chinese; }
}
int _math;
public int Math
{
get { return _math; }
}
int _english;
public int English
{
get { return _english; }
}
----------
public void Say()
{
Console.WriteLine("我叫{0},今年{1}岁了,是{2}生,语文{3};数学{4};英语{5};", this.name, this.Age, this.Gender, this.Chinese, this.Math, this.English);
}
}
program中取值: 构造函数
class Program
{
static void Main(string[] args)
{
Student stu = new Student("张三", 19, '男', 90, 90, 90); //构造函数
stu.Say();//调用显示
Console.WriteLine("==============================="); //分隔符
Student xlStu = new Student("小兰", '女'); //构造函数
xlStu.Say(); //调用显示
Console.ReadKey();
}
}
显示结果:
解释:其中小兰的年龄是默认的,其他的没有写则没有分。
本文介绍了构造方法在对象初始化过程中的作用,包括解决赋初值时重复书写对象名的问题及设置只读属性。通过具体示例展示了如何使用不同参数的构造方法来创建并初始化对象。
2106





