一、为字段赋值的两种方式:1. 通过属性的形式,2. 通过构造函数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test { class Program { static void Main(string[] args) { Person p = new Person(‘中‘); //p.Name = "李四"; //p.Age = -19; //Console.WriteLine(p.Age); Console.WriteLine(p.Gender); Console.ReadKey(); } } class Person { //字段、属性、函数、构造函数.... //字段:存储数据 //属性:保护字段 get set //函数:描述对象的行为 //构造函数:初始化对象,给对象的每个属性进行赋值 string _name; public string Name//张三 { get { return _name; }//去属性的值 set { if (value != "张三") { value = "张三"; } _name = value; }//给属性赋值 } int _age; public int Age { get { if (_age < 0 || _age > 100) { return _age = 18; } return _age; } set { _age = value; } } public char Gender { get; set; } /// <summary> /// 通过构造函数的形式给字段赋值 /// </summary> /// <param name="gender"></param> public Person(char gender) { if (gender != ‘男‘ && gender != ‘女‘) { gender = ‘男‘; } this.Gender = gender; } } }
二、3个关键字的总结:new,this,base。
1. new:创建对象,隐藏父类成员
创建对象:Student s = new Student();
隐藏父类成员:如果使用非重写的方法,需要用关键字new来进行覆盖,具体代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Student s = new Student(); } } class Person { public void SayHello() { Console.WriteLine("我是人类"); } } class Student : Person { /// <summary> /// 如果使用非重写的方法,需要用关键字new来进行覆盖 /// </summary> public new void SayHello()//彻底隐藏了父类的SayHello() { Console.WriteLine("我是学生"); } } }
2. this:代表当前类的对象。
class Teacher { public string Name { get; set; } public int Age { get; set; } public char Gender { get; set; } public int Chinese { get; set; } public int Math { get; set; } public int English { get; set; } public Teacher(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 Teacher(string name, int age, char gender) : this(name, age, gender , 0, 0, 0) { } public Teacher(string name, int chinese, int math, int english) : this(name, 0, ‘\0‘, chinese, math, english) { } public void SayHi() { Console.WriteLine("我叫{0},今年{1}岁了,我是{2}生", this.Name, this.Age, this.Gender); } public void ShowScore() { Console.WriteLine("我叫{0},我的总成绩是{1},平均成绩是{2}", this.Name, this.Chinese + this.Math + this.English, (this.Chinese + this.Math + this.English) / 3); } }
3. base:调用父类的成员
class Person { public void SayHello() { Console.WriteLine("我是人类"); } } class Student : Person { /// <summary> /// /// </summary> public new void SayHello()//彻底隐藏了父类的SayHello() { Console.WriteLine("我是学生"); } public Student GetStudent() { return this; } /// <summary> /// 调用父类的成员 /// </summary> public void GetPerson() { base.SayHello(); } }