![](/img/trans.png)
[英]How can I have an overloaded constructor call both the default constructor as well as an overload of the base constructor?
[英]Can I call both this and base overloads in a constructor?
我能找到的最接近的線程是這個線程,但是情況有所不同-要調用的基本構造函數是默認線程。 在這里,我需要指定要傳遞的參數。
假設我們有以下情形:
public class Base
{
public string Str;
public Base(string s)
{
Str = s;
}
}
public class A : Base
{
public string Str2;
public A(string str2)
: base(str2)
{
Str2 = str2;
}
public A(string str2, string str)
: base(str)
{
Str2 = str2;
}
}
我想避免在A的第二個構造函數重載中重復相同的邏輯(從技術上講,我可以將所有邏輯包裝到一個減少復制粘貼/提高可維護性的函數中,因為最終所有重載都依賴於相同的代碼。如果沒有其他解決方案)。
我以為我可以先調用A的第一個構造函數重載,然后再調用基數。 但似乎我做不到。
這里的方法是什么?
正確的方法是
public class A : Base
{
public string Str2;
public A(string str2)
: this(str2, str2)
{
}
public A(string str2, string str)
: base(str)
{
Str2 = str2;
}
}
的單參數的構造函數A
調用的2參數構造A
使用相同字符串兩個參數傳遞this(
而不是base(
。然后你刪除單個參數的構造函數的身體,因為所有的工作,是在這兩個做參數構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.