给定以下控制台程序:
class Program
{
private static string _value;
static void Main(string[] args)
{
var t = new Action(() => _value = "foo");
Console.Out.WriteLine("t.Method.IsStatic: {0}", t.Method.IsStatic);
}
}
当使用 VS 2013 针对 .Net 4.5.2 编译时,它将打印
t.Method.IsStatic: true
当使用 VS 2015 针对 .Net 4.5.2 编译时,它将打印
t.Method.IsStatic: false
来自 this问题,我有点理解发生了什么,但我很困惑为什么 VS 版本之间的行为会发生变化。据我了解,2013 年的输出是正确的。
最佳答案
检查以下链接中的答案: Delegate caching behavior changes in Roslyn
基本上发生了什么变化,我从链接的答案中引用@Yuzal:
"Delegate caching behavior was changed in Roslyn. Previously, as stated, any lambda expression which didn't capture variables was compiled into a static method at the call site. Roslyn changed this behavior. Now, any lambda, which captures variables or not, is transformed into a display class:"
他所说的显示类是指生成的私有(private)密封类,其中封装了由 Action 委托(delegate)调用的实例方法。
为什么要进行更改?引用 @Kevin Pilch-Bisson(C# IDE 团队成员):
The reason it's faster is because delegate invokes are optimized for instance methods and have space on the stack for them. To call a static method they have to shift parameters around.
所以基本上评论是不言自明的。您在上面的示例中看到的行为差异是因为他们注意到如果 Action 委托(delegate)调用实例方法比调用静态方法更快,无论 lambda 是否捕获变量。
关于c# - 为什么 Action.Method.IsStatic 对于某些 lambda 表达式在 Visual Studio 2013 和 2015 之间不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152772/