如何在不实例化委托的情况下将方法添加到委托的调用列表中?

How to add methods to the invocation list of a delegate without instantiating the delegate?

我必须将多个方法添加到委托的调用列表中。但是,它们都有与之关联的决策逻辑。因此,在方法附加到委托的调用列表之前有一个 if 块。我可以在不实例化委托的情况下执行此操作吗?代码片段如下所示:

public delegate void SomeDelegate();

static void Method1() {}
static void Method2() {}

static void AddMethodsToInvocationList()
{
    SomeDelegate someDelegate = new SomeDelegate();
    if (someLogic1) someDelegate += Method1;
    if (someLogic2) someDelegate += Method2;
}

基本上,我希望能够在不将任何方法作为参数传递的情况下创建委托实例。但是,如果我尝试在不将任何方法作为参数传递的情况下实例化委托,我会收到 "does not contain a constructor that takes 0 arguments" 错误的编译器错误。

如果其他人有更好的方法,我也愿意以不同的方式解决这个问题。但是,必须使用委托。

感谢您的帮助。非常感谢。

您可以简单地将其初始化为null。这是没有添加任何操作的多播委托的惯用值。