C# 匿名方法 和 lambda 表达式
原创
©著作权归作者所有:来自51CTO博客作者覺醒的原创作品,请联系作者获取转载授权,否则将追究法律责任
匿名只是用一次。以后用的都是 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());
}
输出:
参考:
1.link-01 // B 站传智播客