构造函数
作用:帮助我们快速初始化对象(给对象的每个属性依次的赋值) 减少代码冗余
构造函数是一个特殊的方法:创建对象的时候会先执行构造方法,要是子类继承父类的话,创建子类对象会默认执行父类的无参构造函数。
1、构造函数没有返回值,连void也不能写。
2、构造函数的名称必须跟类名一样。
提示:为方便查看类写在一个文件中!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
static void Main(string[] args) { Student s = new Student("张三",25,"男"); //s.Name = "张三"; //s.Age = 22; //s.Sex = "男"; s.Prosen(); Student m = new Student("李四",28,"女"); //m.Name = "李四"; //m.Age = 24; //m.Sex = "春"; m.Proson(); } student类 public class Student { private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } private string _sex; public string Sex { get { return _sex; } set { if (value != "男" && value != "女") { value = "男"; } _sex = value; }//字段一般写在类当中 } public Student(string name,int age,string sex)//构造函数 { this.Name = name; this.Age = age; this.Sex = sex; } public void Prosen() { Console.WriteLine("我叫{0}今年{1}岁性别{2}", this.Name, this.Age, this.Sex); } public void Proson() { Console.WriteLine("我叫{0}今年{1}岁性别{2}", this.Name, this.Age, this.Sex); Console.ReadKey(); } } |