C# 匿名方法 和 lambda 表达式

匿名只是用一次。以后用的都是 lambda 表达式,一般很少会用匿名方法。

给委托赋值的时候才会用到它。有委托变量时才会用。

匿名方法不能直接在类中定义,而是在给委托变量赋值的时候,需要赋值一个方法,此时可以“现做现卖”,定义一个匿名方法传递给该委托。

ProcessWordDelegate p = delegate(string s)
    Console. WriteLine(s);
}; // 注意这里有分号

public delegate void ProcessWordDelegate(string s);

无参数无返回值

static void Main(string[] args)
{
    Action Test = delegate () {
        Console.WriteLine("匿名方法:无参数无返回值。");
    };
    Test();
}

改成 lambda 表达式:

static void Main(string[] args)
{
    Action Test =  () => {
        Console.WriteLine("匿名方法:无参数无返回值。");
    };
    Test();
}

输出:

匿名方法:无参数无返回值。
请按任意键继续. . .

有参数无返回值

static void Main(string[] args)
{
    Action<string> Test = delegate (string msg) {
        Console.WriteLine("匿名方法:" + msg);
    };
    Test("有参数无返回值");
}

改成 lambda 表达式:

static void Main(string[] args)
{
    Action<string> Test =  (string msg) => {
        Console.WriteLine("匿名方法:" + msg);
    };
    Test("有参数无返回值");
}

输出:

匿名方法:有参数无返回值
请按任意键继续. . .

带参数带返回值

static void Main(string[] args)
{
    Func<int, int> Test = delegate (int a) { return a; };
    Console.WriteLine(Test(100));

    Func<int> Test1 = delegate { return 200; };
    Console.WriteLine(Test1());
}

改成 lambda 表达式:

static void Main(string[] args)
{
    Func<int, int> Test =  (int a) => { return a; };
    Console.WriteLine(Test(100));

    Func<int> Test1 = ()=> { return 200; };
    Console.WriteLine(Test1());
}

输出:

100
200
请按任意键继续. . .



参考:
1.link-01 // B 站传智播客

posted @   double64  阅读(184)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示