简体   繁体   English

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

[英]Are extension methods guaranteed to return equal delegates

According to Jon Skeet's answer anonymous functions are not guaranteed to return equal delegates:根据 Jon Skeet 的回答,匿名函数不能保证返回相等的代表:

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. C# 规范明确指出 (IIRC) 如果您有两个匿名函数(匿名方法或 lambda 表达式),它可能会或可能不会从该代码创建相等的委托。 (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 :为了简单起见,让我们忽略扩展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.这是关于引用的问题,委托只是一个 object 表示方法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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