using System; #region /* /// <summary> /// 类定义 /// </summary> class Person { //成员变量 int name; int height; //成员方法 void eat() { } } class Test { static void Main() { Person baby = new Person(); //对象 baby.name = Person YaoMin = new Person(); //对象 } } */ #endregion class A { //1.如果直接在这里初始化,那么每一个构造函数在编译的时候都会有相应的初始化代码 public int i = 100; public string s = "stone"; public A() { Console.WriteLine("constructor"); } //2.如果成员变量在无参构造函数中初始化,然后在有参构造函数中调用无参构造函数,这样有参构造函数中就不会重复初始化成员变量了 public int i; public string s; public A() { Console.WriteLine("constructor"); i = 100; s = "stone"; } public A(int i):this() { this.i = i; } public A(string s):this() { this.s = s; } public A(int i, string s):this() { this.i = i; this.s = s; } } class Test { static void Main() { //A a = new A(); //Console.WriteLine("i="+a.i); //Console.WriteLine("s="+a.s); A a = new A(); Console.WriteLine("first constructor"); Console.WriteLine(a.i); Console.WriteLine(a.s); Console.WriteLine(); A a1 = new A(1); Console.WriteLine("second constructor"); Console.WriteLine(a1.i); Console.WriteLine(a1.s); Console.WriteLine(); A a2 = new A("I am third constructor"); Console.WriteLine("third constructor"); Console.WriteLine(a2.i); Console.WriteLine(a2.s); Console.WriteLine(); A a3 = new A(3, "I am the forth constructor"); Console.WriteLine("Forth constructor"); Console.WriteLine(a3.i); Console.WriteLine(a3.s); } } |