C#中匿名函数的使用

来源:互联网 发布:js裁剪图片并上传 编辑:程序博客网 时间:2024/06/05 09:17

class Test
{
    delegatevoid TestDelegate(string s);
    staticvoid Test(string s)
    {
       Console.WriteLine(s);
    }

    staticvoid Main(string[] args)
    {
       // 原委托语法需要命名方法初始化
       TestDelegate testDelA = new TestDelegate(Test);

       // C# 2.0: 一个委托可以用内联代码初始化,内敛代码被称为“匿名方法”。
       // 这种方法需要一个字符串作为输入参数
       TestDelegate testDelB = delegate(strings) { Console.WriteLine(s); };

       // C# 3.0. 一个委托可以用一个lambda表达式进行初始化。
       // 该表达式也需要一个字符串作为输入参数(X)。 x的类型由编译器推断
       TestDelegate testDelC = (x) => { Console.WriteLine(x); };

       // 请求委托
       testDelA("Hello. My name isTest and I write lines.");
       testDelB("That's nothing. I'm anonymous.");
       testDelC("I'm a famous author."); 

       //保持在调试模式下打开控制台窗口
       Console.WriteLine("Press any key to exit.");
       Console.ReadKey();
    }
}

原创粉丝点击