【发布时间】:2014-02-11 06:03:59
【问题描述】:
代码:
using System;
using System.Collections.Generic;
namespace so {
public abstract class Feature {
public void doIt() {
Console.WriteLine( GetType().FullName );
}
}
class A : Feature { }
class B : Feature { }
class C : Feature { }
public class SSCCE {
event EventHandler Click;
static void Main( string[] args ) {
SSCCE sscce = new SSCCE();
List<Feature> features = new List<Feature>();
features.Add( new A());
features.Add( new B() );
features.Add( new C() );
foreach ( Feature feature in features ) {
sscce.Click += ( object sender, EventArgs e ) => { feature.doIt(); };
}
sscce.Click.Invoke( null, null );
}
}
}
预期结果:
so.A
so.B
so.C
观察结果:
so.C
so.C
so.C
在 java 中,foreach 循环中 Feature 前面的 final 关键字允许在 .doIt() 之前的 lambda 动作的主体中使用 feature 值。
C#中有什么好的语法?
【问题讨论】:
-
你使用的是什么版本的 C#?
-
我使用的是 Microsoft Visual C# 2010,编译器在哪里?它叫什么名字?
-
Jon Skeet 有一个有用的页面。长话短说,您可能使用的是 C# 4.0 或更早版本:csharpindepth.com/Articles/Chapter1/Versions.aspx 此修复直到 C# 5 才引入。