2017-08-27 92 views
1

是否有任何方法將「this」傳遞給基礎構造函數?將「this」傳遞給基礎構造函數

abstract class Base<TSelf> 
{ 
    public ICollection<TSelf> List; 

    public Base(ICollection<TSelf> list, TSelf self) 
    { 
     List = list; 
     List.Add(self); 
    } 
} 

class Implementation : Base<Implementation> 
{ 
    public Implementation() : base(new List<Implementation>(), this) 
    { 
    } 
} 

顯然有在this傳遞給baseImplementation構造一個編譯錯誤。

我也沒有看到任何方式實例listBase級別。

回答

6

不,您不能在構造函數初始值設定項中使用this。之後您必須添加電話Add(this) - 但您可以在Base<TSelf>構造函數中執行此操作,只要您投射到TSelf即可。不幸的是,您需要先將this轉換爲object,然後才能將其轉換爲TSelf,原因相當複雜,原因是類型參數允許進行轉換。

雖然您可以在Base構造函數中創建List<TSelf>,但沒有任何問題。這裏是展示這兩個示例代碼:

abstract class Base<TSelf> 
{ 
    // Let's make it a property rather than a public field... 
    public ICollection<TSelf> List { get; } 

    public Base() 
    { 
     List = new List<TSelf>(); 
     // This will obviously fail if you try to create a `Base<Foo>` 
     // from a class that isn't a Foo 
     TSelf selfThis = (TSelf) (object) this; 
     List.Add(selfThis); 
    } 
} 

class Implementation : Base<Implementation> 
{ 
} 

您可以將約束添加到TSelf,使鑄造失敗不太可能意外但不是不可能的:

abstract class Base<TSelf> where TSelf : Base<TSelf> 

這不會阻止你書寫

class Implementation : Base<Implementation> {} 
class Evil : Base<Implementation> {} 

然後,當您構建Evil的實例時,您正在嘗試廣告d一Evil參考List<Implementation>這不能工作...和演員無法阻止你得到那麼遠。

+0

在鑄造「TSelf」之前將'this'鑄造到'object'是解決方案! –

+0

關於你的評論_This顯然會失敗:這不能用'where T:Base'強制執行嗎? –

+0

@ManuelFaux:是的,會提到的。 –