简体   繁体   中英

Are extension methods guaranteed to return equal delegates

According to Jon Skeet's answer anonymous functions are not guaranteed to return equal delegates:

The C# specification explicitly states (IIRC) that if you have two anonymous functions (anonymous methods or lambda expressions) it may or may not create equal delegates from that code. (Two delegates are equal if they have equal targets and refer to the same methods.)

example of problematic code given

button.Click += (s, e) => MessageBox.Show("Woho");
button.Click -= (s, e) => MessageBox.Show("Woho");

Is this the same case for for extension methods as well? For sake of sample simplicity, lets ignore whether it is good idea to extend string :

var text = "Woho";   
// extension method body is MessageBox.Show(text)
button.Click += text.ShowMessageBoxExtension; 
button.Click -= text.ShowMessageBoxExtension; // can you safely unsubscribe using delegate2?

var delegate1 = text.ShowMessageBoxExtension; 
var delegate2 = text.ShowMessageBoxExtension;
Debug.Assert(delegate1 == delegate2); // or more precisely is this always true?

It's rathre question about references, delegate is just an object representing method. So it all comes down to equality of references, see code below presenting the problem:

// Here we are creating anonymous functions with lambdas,
// every time we create different object.
Action d1 = () => Console.WriteLine("");
Action d2 = () => Console.WriteLine("");
d1==d2;
// false
// Here we use already defined method, one object represenitng the method.
d1 = Console.WriteLine;
d2 = Console.WriteLine;
d1 == d2;
// true

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