2017-03-07 17 views
2

我不知道如果我的理解是錯誤的,但我試圖做類似下面的東西:我可以訪問同一個類的另一個代表中的代表?

我有兩個代表一個基類:

public class Base 
{ 
    public Func<bool> Licensed { get; set; } 
    public Func<bool> Enabled { get; set; } 
}  

而派生類,如下圖所示:

public class Derived : Base 
{ 
    public int Test { get; set; } 
} 

現在,我試圖實例中Main():

static void Main(string[] args) 
{ 
    Derived obj = new Derived() 
    { 
     Licensed =() => { return true; }, 
     Enabled =() => { return Licensed() && true; }, //access above delegate 
    }; 
} 
派生類10

的事情是在Enabled實現,我想訪問略高於分配許可委託。由於不允許,我無法做到這一點。這是否可以以其他方式進行?

回答

4

在對象初始化,不能引用其他屬性。 C#語言規範7.6.10.2對象初始化程序:

對象初始化程序不可能引用正在初始化的新創建的對象 。

但是你可以使用老式的屬性賦值:

var obj = new Derived { Licensed =() => true; }; 
obj.Enabled =() => obj.Licensed() && true; 
2

注意:我提供這個答案顯示出一些其他的方法來OP來解決問題。我不會試圖說不,你不能用一個完整的解釋,因爲這已經被@SergeyBerezovskiy已經回答了。

另一種選擇可能是把它變成流利的API

當我需要設置代表我傾向於認爲他們應該設置一次,永遠不會改變。因此,持有這些代表的財產應該是公開可讀且私人可設置的。

另一方面,應該使用工廠方法和其構造函數private使用創建一個流暢配置的對象。

最後,在流暢鏈中的每個方法也應注入實例配置,而你最終會設置它調用一個作爲參數到配置方法通過委託。

也就是說,你有你在一個非常優雅的方式想要什麼。

public class Derived : Base 
{ 
    private Derived() {} 

    public static Derived Create() => new Derived(); 

    public Func<bool> Licensed { get; private set; } 
    public Func<bool> Enabled { get; private set; } 

    public void LicensedIf(Func<Derived, bool> licensingCondition) 
      => Licensed =() => licensingCondition(this); 

    public void EnabledIf(Func<Derived, bool> enablingCondition) 
      => Enabled =() => enablingCondition(this); 
} 

// Fluent configuration of your *licensable object* gets self-documented 
// by the usage! 
// Oh, and see how EnableIf() takes advantage of C#6's null conditional 
// operator to invoke the "Licensed" delegate if its really set. This is 
// so safe! 
var derived = Derived.Create().LicenseIf(d => true) 
           .EnableIf(d => d.Licensed?.Invoke() && true); 

封裝內委託委託的那個東西會被稱爲在函數式編程鑽營!如果您對此主題感興趣,請參閱What is 'Currying'?

相關問題