C# 如何创建一个构造函数接受另一个类的方法的对象?
我试图创建一个对象,其中包含对其他类中特定方法的调用。您应该能够从对象的实例触发对该方法的调用。据我所知,这样做的方式是委派。这是一种有效的方法吗?从要用作委托的类包装方法,然后像这样设置对象C# 如何创建一个构造函数接受另一个类的方法的对象?,c#,visual-studio,delegates,C#,Visual Studio,Delegates,我试图创建一个对象,其中包含对其他类中特定方法的调用。您应该能够从对象的实例触发对该方法的调用。据我所知,这样做的方式是委派。这是一种有效的方法吗?从要用作委托的类包装方法,然后像这样设置对象 public class ItemCombination { public ItemCombination(string Item1, string Item2, Delegate interaction) { this.Item1 = Item1; thi
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返回类型,或者如果它返回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();
}
}
传入回调绝对是注入功能的合法方式。不过,为了清楚起见,我建议使用键入回调;e、 行动,Func等等,啊,明白了。您甚至可以直接从公共字段交互调用,而不是专门为其创建方法?当然,这完全取决于您希望封装和保护API的程度。例如,如果交互参数为null,您可以在构造函数中设置一个默认实现,或者如果委托为null,您可以在包装器内部调用它。