是否保证扩展方法返回相等的委托

根据Jon Skeet的answer匿名函数,不能保证返回相等的委托:

  

C#规范明确指出(IIRC),如果您有两个   匿名函数(匿名方法或lambda表达式)   否则可能无法从该代码创建平等的委托。 (两名代表是   如果它们具有相同的目标并引用相同的方法,则为相等。)

给出有问题代码的示例

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

扩展方法 是否也一样?为了简单起见,让我们忽略扩展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?
yanxianfeng_5188 回答:是否保证扩展方法返回相等的委托

这是有关引用的棘手问题,委托只是表示方法的对象。因此,一切都归结为引用的相等性,请参见下面的代码介绍问题:

// 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
本文链接:https://www.f2er.com/3118364.html

大家都在问