帮助我们初始化对象,所谓初始化就是给对象的每个属性依次赋值
创建对象的时候执行
class Program { static void Main(string[] args) { Student zs = new Student(-96,65,89);//会进入对应的构造函数中 Console.ReadKey(); } } class Student { string _name; char _gender; int _age; int _chinese; int _math; int _english; public int Sum(int chinese,int math,int english) { int sum = 0; sum = chinese + math + english; return sum; } public Student() { } public Student(int age,int chinese,int english):this("张三",'难',-89,84,98,100)//这个构造函数去调用那个比较全的构造函数,关于这里我有个疑问,明明可以直接去调用那个比较全的构造函数非要写得绕来绕去得 { } public Student(string name,char gender,int age,int chinese,int math,int english) { this.Name = name; if (gender != '男' && gender != '女') gender = '男'; this.Gender = gender; if (age < 0 || age > 140) age = 0; this.Age = age; if (chinese < 0 || chinese > 100) chinese = 60; this.Chinese = chinese; if (math < 0 || math > 100) math = 60; this.Math = math; if (english < 0 || english > 100) english = 60; this.English = english; } public string Name { get => _name; set => _name = value; } public char Gender { get => _gender; set => _gender = value; } public int Age { get => _age; set => _age = value; } public int Chinese { get => _chinese; set => _chinese = value; } public int Math { get => _math; set => _math = value; } public int English { get => _english; set => _english = value; } }
new帮我们做了三件事请,暂时可以这么理解,之前我在一个网站上看到new做的事请很复杂
作用