简体   繁体   中英

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

I have to add multiple methods to the invocation list of a delegate. However, all of them have decision logic associated with them. So, there's an if block before the method gets attached to the invocation list of the delegate. Can I do this without instantiating the delegate. The code snippet looks like the following:

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;
}

Basically, I wish to be able to create an instance of the delegate without passing any methods as parameters. However I get a compiler error with "does not contain a constructor that takes 0 arguments" error, if I try and instantiate the delegate without passing any methods as parameters.

I would also be open to solving this issue a different way if someone else has a better way of doing it. However, delegates have to be used.

Thank you for any help. Much appreciated.

You can simply initialize it to null . That is the idiomatic value for a multicast delegate that doesn't have any operations added to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM