相关疑难解决方法(0)

为什么有些C#lambda表达式编译为静态方法?

正如您在下面的代码中看到的,我已将Action<>对象声明为变量.

有人请让我知道为什么这个动作方法委托表现得像一个静态方法?

为什么它会true在以下代码中返回?

码:

public static void Main(string[] args)
{
    Action<string> actionMethod = s => { Console.WriteLine("My Name is " + s); };

    Console.WriteLine(actionMethod.Method.IsStatic);

    Console.Read();
}
Run Code Online (Sandbox Code Playgroud)

输出:

示例输出示例

.net c# reflection lambda

121
推荐指数
3
解决办法
8143
查看次数

委托Roslyn中的缓存行为更改

给出以下代码:

public class C
{
    public void M()
    {
        var x = 5;
        Action<int> action = y => Console.WriteLine(y);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用VS2013,.NET 4.5.查看反编译代码时,我们可以看到编译器在调用站点缓存委托:

public class C
{
    [CompilerGenerated]
    private static Action<int> CS$<>9__CachedAnonymousMethodDelegate1;
    public void M()
    {
        if (C.CS$<>9__CachedAnonymousMethodDelegate1 == null)
        {
            C.CS$<>9__CachedAnonymousMethodDelegate1 = new Action<int>(C.<M>b__0);
        }
        Action<int> arg_1D_0 = C.CS$<>9__CachedAnonymousMethodDelegate1;
    }
    [CompilerGenerated]
    private static void <M>b__0(int y)
    {
        Console.WriteLine(y);
    }
}
Run Code Online (Sandbox Code Playgroud)

查看在Roslyn中反编译的相同代码(使用TryRoslyn),产生以下输出:

public class C
{
    [CompilerGenerated]
    private sealed class <>c__DisplayClass0
    {
        public static readonly …
Run Code Online (Sandbox Code Playgroud)

.net c# compiler-construction roslyn c#-6.0

30
推荐指数
2
解决办法
2540
查看次数

标签 统计

.net ×2

c# ×2

c#-6.0 ×1

compiler-construction ×1

lambda ×1

reflection ×1

roslyn ×1