[英]How can I create a method whose argument is a function whose argument can be an object from any class extending a given class?
[英]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.