一:委托:数据类型,像类一样
和直接调用函数的区别:用委托可以指向任意的函数,哪怕之前没有定义也可以,而不受限几种
class delegate_
{
delegate string ProcessDelegate(string s); //1.声明委托
static void ProcessIntArray(string[] str, ProcessDelegate p)
{
for (int i = 0; i < str.Length; i++)
str[i] = p(str[i]); //使用委托函数
Console.WriteLine("test end");
foreach (string i in str)
Console.WriteLine(i);
}
public static string Change(string s) {
s = "=" + s.ToUpper() + "=";
return s;
}
static void Main(string[] args) {
string[] values = new string[] { "Aa", "Bb" };
ProcessDelegate pd = new ProcessDelegate(Change); //2.创建委托,使用change()
ProcessIntArray(values,pd);
}
}
我感觉委托就是克隆方法---》先学吧 不知道有什么用。。。。
二:Lambda
学到这,我才知道委托好6
声明委托类:
public delegate int AddDelegate(int n1, int n2, int n3);
public delegate int AddDelegate1(params int[] arr);
public delegate void MyDelegate1(string msg);
public delegate void MyDelegate();
主函数:
<span style="font-size: 10px;"> static void Main() {
//1.无参数,无返回值的一个匿名方法
MyDelegate m1 = delegate () {Console.WriteLine("1. hello word");};
m1();
MyDelegate l1 = () => { Console.WriteLine("1. lambda test"); };
l1();
//2.有参数,无返回值的匿名方法(单个)
MyDelegate1 m2 = delegate (string msg)
{
Console.WriteLine(msg);
};
m2("2. zzj");
MyDelegate1 l2 = m => { Console.WriteLine(m); };//类型为什么可以去掉?因为委托限定必须是string
l2("2. lambda");
//3.有参数,有返回值(多个)
AddDelegate m3 = delegate (int n1,int n2,int n3) {
return n1 + n2 + n3;
};
Console.WriteLine("3. "+m3(1, 2, 3));
AddDelegate l3 = (x, y, z) => { return x + y + z; };
Console.WriteLine("3. " + l3(1, 2, 3));
//4.数组
AddDelegate1 ad1 = (arr) =>
{
for (int i = 0; i < arr.Length; i++)
Console.WriteLine("arr test ="+arr[i]);
return arr.Sum();
};
Console.WriteLine("4. "+ad1(1,2,3,4,5,6));
}</span>
结果
1. hello word
1. lambda test
2. zzj
2. lambda
3. 6
3. 6
arr test =1
arr test =2
arr test =3
arr test =4
arr test =5
arr test =6
4. 21
请按任意键继续. . .
这里最重要的我觉得是4, params int[] arr的定义使用
三:Action Fuc Lambda->List<>
#region 泛型委托
#region Action
Console.WriteLine();
Console.WriteLine("------以下为繁泛型---");
//1
Action action1 = new Action(M1);
action1();
//2。string参数,无返回
MyGenreicDelegate<string> md = M1;
md("test str");
//3
Action<string> a1 = m => { Console.WriteLine(m); };
a1("a1 test");
//4
Action<int, int> a2 = (x, y) => { Console.WriteLine(x + y); };
a2(1, 2);
#endregion
#region Func
Console.WriteLine();
Console.WriteLine("------func");
#endregion
#region lambda--> List<>
Console.WriteLine();
Console.WriteLine("------List");
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
IEnumerable<int> ie = list.Where(x => { return x > 6; });
foreach (var item in ie)
Console.WriteLine(item);
#endregion
#endregion
这个里面我看到lingq的使用,这是切入点
<span style="color:#ff0000;"> IEnumerable<int> ie = list.Where(x => { return x > 6; });</span>