//Lambda运算符=>
//Lambda运算符的左边是输入参数(如果有)
//右边是表达式或语句块
//无参数
private void OnTest1()
{
Action cb1 = delegate () {
Console.WriteLine("Hello");
};
cb1();
Action cb2 = () => {
Console.WriteLine("Hello");
};
cb2();
}
//有参数
private void OnTest2()
{
Action<string> cb1 = delegate (string name) {
Console.WriteLine(name);
};
cb1("小明");
Action<string> cb2 = name => {
Console.WriteLine(name);
};
cb2("小红");
Action<int> cb3 = x => {
int num = x * 3;
Console.WriteLine(num);
};
cb3(2);
}
//有返回值
public delegate int MyDelegate(int x,int y);//定义委托
private void OnTest3()
{
//MyDelegate mydel = new MyDelegate(GetNum);
MyDelegate mydel = GetNum;
int n1 = mydel(2,3);
Console.WriteLine(n1);//6
mydel = (x, y) => {
return x * y;
};
int n2 = mydel(5,6);
Console.WriteLine(n2);//30
}
private int GetNum(int x,int y)
{
return x * y;
}
private void btnTest1_Click(object sender, RoutedEventArgs e)
{
//OnTest1();
//OnTest2();
OnTest3();
}
}
c# Lambda表达式使用
猜你喜欢
转载自blog.csdn.net/i1tws/article/details/80536844
今日推荐
周排行