
构造函数
作用:帮助我们初始化对象(给对象的每个属性依次的赋值)
构造函数是一个特殊的方法:
1、构造函数没有返回值,连void也不能写。
2、构造函数的名称必须跟类名一样。
创建对象的时候会执行构造函数。
构造函数是可以重载的。
**
类当中会有一个默认的无参数的构造函数,当你写一个新的构造函数后,不管是有参数的还是无参数的,那个默认的无参数的构造函数都会消失。
new关键字
Person zsPerson= new Person();
new 3个作用:
1、在内存中开辟了一块空间。
2、在开辟的空间中创建对象。
3、调用对象的构建函数进行初始化对象。
using System;using System.Collections.Generic;using System.Text;namespace _050_面对对象初级_5_类的构造函数{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;}private string _name;public string Name{get { return _name; }set { _name = value; }}private int _age;public int Age{get { return _age; }set {if (value < 0 || value > 100){value = 0;}_age = value; }}private char _gender;public char Gender{get {if (_gender != '男' && _gender != '女'){return _gender = '×';}return _gender; }set { _gender = value; }}private int _chinese;public int Chinese{get { return _chinese; }set { _chinese = value; }}private int _math;public int Math{get { return _math; }set { _math = value; }}private int _english;public int English{get { return _english; }set { _english = value; }}public void SayHello(){Console.WriteLine("我叫{0},今天{1}岁了,是个{2}生", this.Name, this.Age, this.Gender);}public void ShouScore(){Console.WriteLine("我的总成绩是{0},平均成绩是{1}", (this.Chinese + this.Math + this.English), (this.Chinese + this.Math + this.English) / 3);}}}
using System;namespace _050_面对对象初级_5_类的构造函数{class Program{static void Main(string[] args){Student zsStudent = new Student("张三", 18, '男', 100, 100, 100);//zsStudent.Name = "张三";//zsStudent.Age = 18;//zsStudent.Gender = '男';//zsStudent.Chinese = 100;//zsStudent.Math = 100;//zsStudent.English = 100;zsStudent.SayHello();zsStudent.ShouScore();Student xlStudent = new Student("小兰", 17, '女', 99, 99, 99);//xlStudent.Name = "小兰";//xlStudent.Age = 19;//xlStudent.Gender = '女';//xlStudent.Chinese = 99;//xlStudent.Math = 99;//xlStudent.English = 99;xlStudent.SayHello();xlStudent.ShouScore();Console.ReadKey();}}}
