对象初始化器(语法糖)
Person p = new Person("zxh") { Name = "yzk", Age = 18, Email = "yzk@rupeng.com" };
1 //List<int> list = new List<int>(); 2 //list.Add(10); 3 //list.Add(20); 4 5 List<int> list = new List<int> { 10, 20, 30, 40 }; 6 foreach (int item in list) 7 { 8 Console.WriteLine(item); 9 } 10 Console.ReadKey();
lthis:
•1.作为当前类的对象,可以调用类中的成员。this.成员(调用成员,自己)
•2.调用本类的其他构造函数。:this()(调用构造函数,自己)
lbase :
•1.调用父类中的成员(调用成员,父类)base点不出子类独有成员。
•2.调用父类中的构造函数(调用构造函数,父类)
•当调用从父类中继承过来的成员的时候,如果子类没有重写则this.成员;与base.成员;没有区别。如果子类重写了父类成员,则this.成员;调用的是子类重写以后的。base.成员;调用的依然是父类的成员。
l子类构造函数必须指明调用父类哪个构造函数
1 namespace _06通过this调用自己的构造函数 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 8 } 9 } 10 11 public class MyClass 12 { 13 public MyClass() 14 { 15 16 } 17 public MyClass(string name) 18 { 19 20 } 21 } 22 23 public class Person : MyClass 24 { 25 public Person(string name, int age, string email, double salary) 26 { 27 this.Name = name; 28 this.Age = age; 29 this.Email = email; 30 this.Salary = salary; 31 } 32 33 //this作用1:在当前类的构造函数后面通过:this来调用当前类自己的其他构造函数。 34 public Person(string name) 35 : this(name, 0, null, 0) 36 { 37 // this.Name = name; 38 } 39 public Person(string name, int age) 40 : this(name, age, null, 0) 41 { 42 //this.Name = name; 43 //this.Age = age; 44 } 45 public Person(string name, string email) 46 : this(name, 0, email, 0) 47 { 48 //this.Name = name; 49 //this.Email = email; 50 } 51 52 53 public string Name 54 { 55 get; 56 set; 57 } 58 public int Age 59 { 60 get; 61 set; 62 } 63 public string Email 64 { 65 get; 66 set; 67 } 68 69 public double Salary 70 { 71 get; 72 set; 73 } 74 } 75 }
在一般情况下,如果子类继承了父类的成员,那么在子类中,通过this.成员或baes.成员都是访问的是一样的。除非父类中的成员子类继承后又重写了。