Unable to get first method name in multicast deletion

I have this code:

public void AddMenuRow(FuncInvoker i_FuncToAdd) // add a row to menu. { if (d_Lines == null) { d_Lines = new FuncInvoker(i_FuncToAdd); } else { d_Lines += i_FuncToAdd; } } 

to add methods to the call list.

And now I want to print the name of each method on the console, so I did this:

 public void Show() { int count = 1; string name = null; Console.WriteLine(m_Title); foreach (FuncInvoker list in d_Lines.GetInvocationList()) { name = list.Method.Name; Console.WriteLine((count++) + ". " + name); } } 

The problem is the first method name, which for some reason always displays "invoke". The following methods in delegate deletion work fine.

Can someone help me? I have tried everything.

+4
source share
1 answer

In this line:

 d_Lines = new FuncInvoker(i_FuncToAdd); 

... you are actually creating a new delegate instance that wraps the original delegate. The target method of this new delegate will be the Invoke method of the original delegate (assuming it is unicast), which explains the behavior you observe.

The obvious workaround is not to use the shell and just copy the reference to the original delegate to the variable:

 d_Lines = i_FuncToAdd; 

But you can also completely abandon your "special case" branch and just do it (if the argument cannot be null ):

 public void AddMenuRow(FuncInvoker i_FuncToAdd) { d_Lines += i_FuncToAdd; } 

This will work just fine since Delegate.Combine (this is what the syntax += means) to return a link to the second delegate if the first delegate is null rather than throwing an exception.

+5
source

Source: https://habr.com/ru/post/1390969/


All Articles