簡體   English   中英

如何創建其構造函數接受另一個類的方法的對象?

[英]How do I create an object whose constructor accepts a method from another class?

我正在嘗試創建一個對象,該對象包含對其他類中特定方法的調用。 您應該能夠從對象的實例觸發對該方法的調用。 據我設法弄清楚,這樣做的方法是委托。 那么這是一種有效的解決方法嗎? 從您要用作委托的類中包裝一個方法,然后像這樣設置您的對象?

public class ItemCombination
{
    public ItemCombination(string Item1, string Item2, Delegate interaction)
    {
        this.Item1 = Item1;
        this.Item2 = Item2;
        this.interaction = interaction;
    }

    public string Item1 { get; set; }
    public string Item2 { get; set; }
    public Delegate interaction { get; set; }

    public void Interact()
    {
       interaction();
    }
}

這正是委托的用途,但是正如注釋中已經提到的那樣,如果委托具有void返回類型,則應該使用類型化委托,即System.Action<T...>Func<T..., R>如果它返回R的實例。 您的示例將如下所示:

public class ItemCombination
{
    public ItemCombination(string Item1, string Item2, Action interaction)
    {
        this.Item1 = Item1;
        this.Item2 = Item2;
        this.interaction = interaction;
    }

    public string Item1 { get; set; }
    public string Item2 { get; set; }
    public Action Interaction { get; set; }

    public void Interact()
    {
       // safeguard against null delegate
       Interaction?.Invoke();
    }
}

暫無
暫無

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

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