根据您在这里提出的问题和对Jon答案的评论,我认为您混淆了多个概念。 为了确保清晰:
- 支持给定Lambda的委托的方法始终相同。
- 支持“相同”的Lambda的委托的方法被允许是相同的,但在实践中,在我们的实现中,它通常不是相同的。
- 针对给定Lambda创建的委托实例可能会或可能不会始终相同,具体取决于编译器对其进行缓存时的智能程度。
因此,如果您有类似以下的内容:
for(i = 0
M( ()=>{} )
每次调用M时,你会得到同一个委托实例,因为编译器很聪明并会生成相同的实例。
static void MyAction() {}
static Action DelegateCache = null;
...
for(i = 0; i < 10; ++i)
{
if (C.DelegateCache == null) C.DelegateCache = new Action ( C.MyAction )
M(C.DelegateCache);
}
如果您拥有
for(i = 0; i < 10; ++i)
M( ()=>{this.Bar();} )
然后编译器会生成
void MyAction() { this.Bar(); }
...
for(i = 0; i < 10; ++i)
{
M(new Action(this.MyAction));
}
您每次都会获得一个新的委托,但该委托具有相同的方法。
编译器被允许(但实际上目前并未这样做)生成。
void MyAction() { this.Bar(); }
Action DelegateCache = null;
...
for(i = 0; i < 10; ++i)
{
if (this.DelegateCache == null) this.DelegateCache = new Action ( this.MyAction )
M(this.DelegateCache);
}
在这种情况下,如果可能,您将始终获得相同的委托实例,并且每个委托都将由同一方法支持。
如果您有
Action a1 = ()=>{};
Action a2 = ()=>{};
实际上,编译器将其生成为:
static void MyAction1() {}
static void MyAction2() {}
static Action ActionCache1 = null;
static Action ActionCache2 = null;
...
if (ActionCache1 == null) ActionCache1 = new Action(MyAction1);
Action a1 = ActionCache1;
if (ActionCache2 == null) ActionCache2 = new Action(MyAction2);
Action a2 = ActionCache2;
然而编译器被允许检测到这两个lambda表达式是相同的并且生成
static void MyAction1() {}
static Action ActionCache1 = null;
...
if (ActionCache1 == null) ActionCache1 = new Action(MyAction1);
Action a1 = ActionCache1;
Action a2 = ActionCache1;
现在清楚了吗?
GetCurrentMethod
并不具有相同的效果... - user541686public static Local<TValue> Instance<TScope>( Func<TScope> scope )
,其中将() => this
传递给作用域。在这种情况下,它仍然返回相同的委托。 - Steven Jeuris