C# 匿名方法 和 lambda 表达式

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

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

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

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

public delegate void ProcessWordDelegate(string s);

无参数无返回值

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

改成 lambda 表达式:

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

输出:

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

有参数无返回值

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

改成 lambda 表达式:

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

输出:

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

带参数带返回值

1
2
3
4
5
6
7
8
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 表达式:

1
2
3
4
5
6
7
8
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
2
3
100
200
请按任意键继续. . .




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

感谢支持!