簡體   English   中英

我可以在同一個類的另一個委托中訪問委托嗎?

[英]Can I access delegate inside another delegate of same class?

我不知道我的理解是否有誤,但是我正在嘗試執行以下操作:

我有兩個代表的基類:

 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():實例化派生類Main():

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

事情是在Enabled實現中,我想訪問剛剛分配的Licensed委托。 我無法實現此目標,因為這是不允許的。 這可以通過其他方式實現嗎?

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

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

但是您可以使用老式的屬性分配:

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

注意 :我提供此答案是為了向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);

在函數編程中將委托封裝在委托中的事情稱為currying 請參閱什么是“固化”? 如果您對此主題感興趣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM