如何使用匿名方法?

本文介绍了 C# 中从委托到匿名方法再到 Lambda 表达式的演进过程,通过示例对比了不同版本 C# 中声明委托的方法,并探讨了各自适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 表面上看,匿名方法是C#2.0的一个新特性,但是本质上和1.0的delegate有很密切的关系,可以认为是delegate的升级版。当然,到了C#3.0有进一步升级,变成了lambda表达式,其表现形式越来越简洁。可以看出来C#语言的一个进化方向就是不断地去贴近人的思维,简化代码编写的逻辑,精简代码量。下面先看一个例子:

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required
        // initialization with a named method.
        TestDelegate testdelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testdelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
*/

 

可以看出来,匿名方法采用了一种内联的方式,封装了delegate的实现。这样做的好处是,当我们需要一个简单的delegate实体对象时,不必像以前一样,声明一个delegate的变量,并且将其绑定到一个方法。例如我们点击一个button,编写click响应事件函数,其实我们一般很少去直接调用button_click函数,因此没必要写着么繁杂的代码。

当然,不足之处也是显而易见的,就是当我们需要处理比较复杂的逻辑时,这种内敛的方式就会使的代码显得冗长,这个时侯还是用delegate的表达方式要好。

最后看看lambda表达式。它需要编写的代码量就更少了:(参数列表)=>{表达式},但是请注意,这些技术背后的原理都是一样的。当然,要了解lambda,我们还需要了解表达式树和LINQ。这个在以后的文章中再分别做详细说明。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值