Some examples about how to write anonymous method and lambda expression

本文介绍了C#中Lambda表达式和匿名方法的应用,包括如何使用Lambda表达式创建委托并作为参数传递给其他方法,以及如何利用匿名方法简化代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LandmaExpressionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //anonymous method
            Action ac = delegate() { Console.WriteLine("hello delegate"); };
            ac();

            //Use Action<T> to create anonymous method with parameters
            Action<string> ac2 = delegate(string strMessage) { Console.WriteLine(strMessage); };
            ac2("hello world2");

            //Pass the anonymous method to another method as parameter
            ActionHelper(delegate(string strMessage) { Console.WriteLine(strMessage); });

            //use landmar expression as parameter to another method
            ActionHelper(fw => Console.WriteLine(fw));

            //Use lambda expression as a delegate
            Action ac3 = () => Console.WriteLine("hello ac3");
            ac3();


        }

        public delegate void DisplayMessageDelegate(string strMesssage);

        public static void ActionHelper(Action<string> ac)
        {
            ac("hello world3");
        }

        //Useful references
        //1. http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
        //2. http://msdn.microsoft.com/en-us/library/bb549151.aspx
        //3. http://msdn.microsoft.com/en-us/library/bb397687.aspx
        //4. http://msdn.microsoft.com/en-us/library/bb534960.aspx
    }
}

 

转载于:https://www.cnblogs.com/xiaxi/archive/2011/10/31/2230229.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值