扩展方法是否保证 return 平等代表
Are extension methods guaranteed to return equal delegates
根据 Jon Skeet 的 answer 匿名函数不能保证 return 平等代表:
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.)
给出的问题代码示例
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?
这是一个关于引用的问题,委托只是一个代表方法的对象。所以这一切都归结为引用相等,请参阅下面的代码来解决问题:
// 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
根据 Jon Skeet 的 answer 匿名函数不能保证 return 平等代表:
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.)
给出的问题代码示例
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?
这是一个关于引用的问题,委托只是一个代表方法的对象。所以这一切都归结为引用相等,请参阅下面的代码来解决问题:
// 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