.Net C#语法 构造函数中this和base

  1. public class TestClassA  
  2. {  
  3.     public TestClassA()  
  4.     {  
  5.         Console.WriteLine("我是在TestClassA中的TestClassA()构造函数中");  
  6.     }  
  7.     public TestClassA(string a, string b)  
  8.     {  
  9.         Console.WriteLine("我是在TestClassA中的TestClassA(string a, string b)构造函数中");  
  10.     }  
  11.     public TestClassA(string a)  
  12.         : this(a, "b")  
  13.     {  
  14.         Console.WriteLine("我是在TestClassA中的TestClassA(string a): this(a, \"b\")构造函数中");  
  15.     }  
  16. }  
  17.   
  18. public class TestClassB : TestClassA  
  19. {  
  20.     public TestClassB()  
  21.     {  
  22.         Console.WriteLine("我是在TestClassB中的TestClassB()构造函数中");  
  23.     }  
  24.     public TestClassB(string a, string b)  
  25.         : base(a, b)  
  26.     {  
  27.         Console.WriteLine("我是在TestClassB中的TestClassB(string a, string b): base(a, b)构造函数中");  
  28.     }  
  29.   
  30.     public TestClassB(string a)  
  31.         : this(a, "b")  
  32.     {  
  33.         Console.WriteLine("我是在TestClassB中的TestClassB(string a, string b): this(a, \"b\")构造函数中");  
  34.     }  
  35. }  



  1. Console.WriteLine("TestClassA Father1 = new TestClassA();运行结果:");   
  2. TestClassA Father1 = new TestClassA();   
  3. Console.WriteLine();   
  4. Console.WriteLine("TestClassA Father2 = new TestClassA(\"f2\", \"f2\");运行结果:");   
  5. TestClassA Father2 = new TestClassA("f2""f2");   
  6. Console.WriteLine();   
  7. Console.WriteLine("TestClassA Father3 = new TestClassA(\"f3\");运行结果:");   
  8. TestClassA Father3 = new TestClassA("f3");   
  9. Console.WriteLine();  
  10. Console.WriteLine("TestClassB Son1 = new TestClassB();运行结果:");  
  11. TestClassB Son1 = new TestClassB();               
  12. Console.WriteLine();  
  13. Console.WriteLine("TestClassB Son2 = new TestClassB(\"s2\", \"s2\");运行结果:");  
  14. TestClassB Son2 = new TestClassB("s2""s2");  
  15. Console.WriteLine();               
  16. Console.WriteLine("TestClassB Son3 = new TestClassB(\"s3\");运行结果:");  
  17. TestClassB Son3 = new TestClassB("s3");  
  18. Console.WriteLine();  



分析:

this:调用的是本身,不能调用父类和子类的

base:调用父类的,不能调用本身的,但别人继承,可以调用

从中也可以得出另外个结果构造函数的运行过程 先从基类开始构造再到类本身


posted on 2012-09-27 15:43  dudumao  阅读(331)  评论(0编辑  收藏  举报

导航

阿里云