正如您在下面的代码中所看到的,我已将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();
}

输出:

示例输出样本

推荐答案

这很可能是因为没有闭包,例如:

int age = 25;
Action<string> withClosure = s => Console.WriteLine("My name is {0} and I am {1} years old", s, age);
Action<string> withoutClosure = s => Console.WriteLine("My name is {0}", s);
Console.WriteLine(withClosure.Method.IsStatic);
Console.WriteLine(withoutClosure.Method.IsStatic);

这将为withClosure输出false,为withoutClosure输出true.

当您使用lambda表达式时,编译器会创建一个小类来包含您的方法,这将编译成如下所示(实际实现很可能略有不同):

private class <Main>b__0
{
    public int age;
    public void withClosure(string s)
    {
        Console.WriteLine("My name is {0} and I am {1} years old", s, age)
    }
}

private static class <Main>b__1
{
    public static void withoutClosure(string s)
    {
        Console.WriteLine("My name is {0}", s)
    }
}

public static void Main()
{
    var b__0 = new <Main>b__0();
    b__0.age = 25;
    Action<string> withClosure = b__0.withClosure;
    Action<string> withoutClosure = <Main>b__1.withoutClosure;
    Console.WriteLine(withClosure.Method.IsStatic);
    Console.WriteLine(withoutClosure.Method.IsStatic);
}

您可以看到生成的Action<string>个实例实际上指向这些生成的类上的方法.

.net相关问答推荐

.NET Blazor-使用子组件中的处理程序方法进行双向数据绑定

从没有流的EventStore中读取流不存在异常

dotnet ef dbcontext scaffold command --data-annotations 或 -d 命令行参数似乎不起作用

使用 PostAsJsonAsync C# 时出现错误请求

如何计算给定2个字符串的距离相似性度量?

是否可以将 SandCastle 创建的两个页面合并到一个主页中?

process.WaitForExit() 异步

CurrentCulture、InvariantCulture、CurrentUICulture 和 InstalledUICulture 之间的区别

有没有办法以编程方式最小化窗口

简单委托(委托)与多播委托

C# 编译为 32/64 位,或任何 cpu?

修剪数组中的所有字符串

在 .NET 中查找下一个 TCP 端口

VB.NET 与 C# 整数除法

CryptographicException 未处理:系统找不到指定的文件

Guid.Parse() 或 new Guid() - 有什么区别?

判断对象列表是否包含具有特定值的属性

MVC4 HTTP 错误 403.14 - 禁止

找不到 System.Windows.Media 命名空间?

如何从 webclient 获取状态码?