//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();
}
}
//Fun委托
private void Button_Click(object sender, RoutedEventArgs e)
{
//Func<int, string> func = OnTest;
//string str = func(10);
//Console.WriteLine(str);
//Lambda方式 如果只有一条语句,则返回这条语句的返回值
//Func<int, string> func = nn => String.Format("a{0}",nn);
//string str = func(10);
//Console.WriteLine(str);
//Func<int, string> func = nn => {
// String.Format("a{0}", nn);
// return "bb";
//};
//string str = func(10);
//Console.WriteLine(str);
}
private string OnTest(int num)
{
return "a" + num;
}
下面示例:Fun 和 List.Where的使用
//string str = _strlist.Where(s => s == "1");
List<string> a1 = _strlist.Where(s => s == "1").ToList();
List<string> a2 = _strlist.Where(s => {
if(s == "1")
return true;
return false;
}).ToList();
List<string> a3 = _strlist.Where(s => s == "1" || s == "2").ToList();
Func<string, bool> cb = s => {
if (s == "1" || s == "2")
return true;
return false;
};
List<string> a4 = _strlist.Where(cb).ToList();
Func<string, bool> cb2 = delegate (string s) {
if (s == "1" || s == "2")
return true;
return false;
};
List<string> a5 = _strlist.Where(cb).ToList();