2016-08-01 279 views
0

我知道我們可以使用構造函數鏈從其他構造函數調用參數構造函數。從C#中的參數化構造函數調用無參數構造函數?

但是,

public class Program 
    { 
     public static void Main(string[] args) 
     { 
      Console.WriteLine("Hello, world!"); 

      var t1 = new T1("t2"); 


     } 
    } 

    public class T1 
    { 
     public T1() 
     { 
      Console.WriteLine("t1"); 
     } 

     public T1(string s):base() 
     { 
      Console.WriteLine(s); 
     } 
    } 

這似乎並沒有調用基類的構造(不帶任何參數)。

任何想法?

編輯:

當前:打印t2。 t1不在控制檯上。

所以,我已經使出了以下方法:

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     Console.WriteLine("Hello, world!"); 

     var t1 = new T1("t2"); 


    } 
} 

public class T1 
{ 
    private void privateMethod() 
    { 
      Console.WriteLine("common method"); 
    } 

    public T1() 
    { 
     privateMethod(); 
    } 

    public T1(string s):base() 
    { 
     Console.WriteLine(s); 
     privateMethod(); 

    } 
} 

是否有這樣做的更好的方法呢?

+1

這裏的基類在哪裏? –

+2

@MrinalKamboj - 他們打算使用'this'並且錯誤地將'base'指向T1構造函數。在這種情況下,'base'實際上是System.Object' – keyboardP

+2

OP,快速調試提示 - 在Visual Studio中,單擊'base()'並按F12。你會看到它指的是什麼。現在將它換成'this()',然後按F12,你會發現它現在引用了'T1'構造函數。如果您沒有獲得您期望的編程流程,請逐行逐行進行,這有助於找出問題的根源。 – keyboardP

回答

8

您正在尋找this()

public class T1 
{ 
    public T1() 
    { 
     Console.WriteLine("t1"); 
    } 

    public T1(string s) : this() 
    { 
     Console.WriteLine(s); 
    } 
} 
+0

你說得對..我很傻..謝謝:) –

1

您正在尋找的關鍵字thisbase會調用父類(如你擴展類)。

1

當您使用base關鍵字時,實際上您正在調用Object()構造函數。你想使用this關鍵字

public class T1 
{ 
    public T1() 
    { 
     Console.WriteLine("t1"); 
    } 

    public T1(string s) : this() 
    { 
     Console.WriteLine(s); 
    } 
} 
+0

很好的解釋,對於第1行,當你使用** base **關鍵字時,你正在調用Object()構造函數 –

1

正如在其他的答案中提到,調用你必須使用:this()base()調用基類的無參數的構造函數)

但是參數的構造函數,我覺得這是一種不好的做法。構造函數參數是更好地定義類的初始化的參數,因此,無參數的構造函數應該調用它,而不是相反。

即:

public class T1 
{ 
    public T1():this(String.Empty) // <= calling constructor with parameter 
    { 
     Console.WriteLine("t1"); 
    } 

    public T1(string s) 
    { 
     Console.WriteLine(s); 
    } 
} 

而不是:

public class T1 
{ 
    public T1() 
    { 
     Console.WriteLine("t1"); 
    } 

    public T1(string s) : this() // <= calling parameterless constructor 
    { 
     Console.WriteLine(s); 
    } 
} 

順便說一句,似乎語言向使用主構造使用,以及鼓勵去 - Primary constructors(它是一個實驗性功能在C#6中刪除了,不確定是否爲好......)

0

this調用當前類實例,而base父母。