C# lambda 表达式的转换

发布于 2024-08-12 12:07:32 字数 279 浏览 2 评论 0原文

将以下内容转换为 lambda 表达式的方法是什么?

ThreadPool.QueueUserWorkItem(delegate
     {
        Console.WriteLine("Current Thread Id is {0}:",
         Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
      }
    );

What is the way to convert the following into lambda expression?

ThreadPool.QueueUserWorkItem(delegate
     {
        Console.WriteLine("Current Thread Id is {0}:",
         Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
      }
    );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放肆 2024-08-19 12:07:32

您绝对可以将其写为 lambda 表达式:

// The underscore is simply a placeholder for the "state"
// parameter that the WaitCallback delegate expects - you could
// use any character but you must specify one as lamba expressions cannot
// omit parameters like anonymous functions can.
ThreadPool.QueueUserWorkItem((_) =>
    {
        Console.WriteLine("Current Thread Id is {0}:",
        Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
    });

但请记住,lambda 表达式在源代码之外没有任何意义。 C# 编译器会将您的 lambda 表达式直接转换回您现在的代码。

lambda 表达式只是语法糖,可用于表达匿名函数 - 编译器会将其转换为匿名函数或表达式树。

You could definitely write this as a lambda expression:

// The underscore is simply a placeholder for the "state"
// parameter that the WaitCallback delegate expects - you could
// use any character but you must specify one as lamba expressions cannot
// omit parameters like anonymous functions can.
ThreadPool.QueueUserWorkItem((_) =>
    {
        Console.WriteLine("Current Thread Id is {0}:",
        Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
    });

But remember that a lambda expression has no meaning outside of your source code. The C# compiler will convert your lambda expression right back to the code you have now.

A lambda expression is simply syntactic sugar that you can use to express an anonymous function - the compiler will convert this to either an anonymous function or an expression tree.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文