简体   繁体   中英

Is it possible to chain multiple methods to a delegate in one assignment statement?

I want to chain together two (and possibly more in the future) methods to a delegate and just wondered if there is a way to do this in one assignment statement, eg

I have a delegate method signature defined as

public delegate void MaskRequestSection(Request request); 

...and 2 methods that use this signature, namely...

public void MaskCvnSection(Request request)
{
    // do the masking operation
}

public void MaskCardNumberSection(Request request)
{
    // do the masking operation
}

At present, I am using the following to instantiate the delegete, chain the 2 methods to it and then invoke them...

private void HideDetailsInRequest(Request request)
{
    MaskRequestSection maskRequestSection = MaskCvnSection;
    maskRequestSection += MaskCardNumberSection;
    maskRequestSection(request);
}

....I am just curious as to why I can't chain both delegates in one statement like below,

MaskRequestSection maskRequestSection = MaskCardNumberSection+ MaskCvnSection;

...but also if there is another way that it can be done within one declaration. I haven't been able to find anything that specifically addresses this on MSDN, and I'm just asking for my own curiosity.

Thanks in advance.

You can do it with a cast:

var maskRequestSection = (MaskRequestSection) MaskCardNumberSection
       + (MaskRequestSection) MaskCvnSection;

... but you can't do it without one, because the + operator here works on delegates, not method groups. When the compiler sees the binary + operator, it has to work out the type of the expression, and that doesn't take the assignment part into account.

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