正如您在下面的代码中所看到的,我已将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相关问答推荐

无法在Designer、VS2022、. NET 8中打开WinForms表单'

删除数据库项目中的表

PowerShell 5.1和7在使用证书时的区别

C#:如何构造异步/等待代码,其中许多请求是针对相同的、返回缓慢的数据发出的,这可以满足所有请求

有没有更好的方法使用 Pusher Channels 的批事件发布消息?

.NET Async / Await:状态机如何知道何时继续执行?

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

Erlang 的让它崩溃的哲学 - 适用于其他地方吗?

是否可以模拟 .NET HttpWebResponse?

有什么方法可以使用 .NET 应用程序使用 git 吗?

你如何调试 MVC 4 API 路由?

使用 C# 设置全局热键

ToLowerInvariant() 有什么问题?

如何使用 Entity Framework Code First CTP 5 存储图像?

如何将 .NET 应用程序编译为本机代码?

如果选中,则更改列表框项的 WPF DataTemplate

如何在 C# 中使用迭代器反向读取文本文件

System.IO.IOException:使用 System.IO.Path.GetTempFileName() 时文件存在 - 解决方案?

Uri.Host 和 Uri.Authority 有什么区别

多行 C# 插值字符串文字