繁体   English   中英

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

[英]Are extension methods guaranteed to return equal delegates

根据 Jon Skeet 的回答,匿名函数不能保证返回相等的代表:

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?

这是关于引用的问题,委托只是一个 object 表示方法。 所以这一切都归结为引用的相等性,请参阅下面的代码来呈现问题:

// 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