c# - 为什么 Action.Method.IsStatic 对于某些 lambda 表达式在 Visual Studio 2013 和 2015 之间不同

标签 c# visual-studio-2013 visual-studio-2015 roslyn

给定以下控制台程序:

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/

相关文章:

c# - 我应该从哪里开始制作基于.NET 框架的RESTful Web 服务?

visual-studio-2013 - TFS/Visual Studio : Move file in the solution without doing an "add-remove"

visual-studio-2015 - 为什么我的SpecFlow测试没有显示在Visual Studio“测试”窗口中?

asp.net - 在 Webform 中设计/拆分悬挂

api - C#、RestSharp、类型或命名空间名称 "HttpBasicAuthenticator"找不到

c# - 为派生的Model类创建不同的ViewModel对象

c# - 比较 mySQL 中的数据值(WPF - C#)

c# - XPathExpression AddSort 失败

c++ - _MSC_VER 是否取决于工具包版本?

visual-studio-2013 - 下载适用于Visual Studio 2013的MSBuild构建工具