委托的使用2
1.找到 委托主体
static void ProgramMothod() {
Console.WriteLine("这是MyDelegate的委托");
}
static void ProgramMothod2(int aValue, int bValue) {
Console.WriteLine($"{aValue}这是MyDelegate2的委托.{bValue}");
}
//注意这个方法传入的时候需要传入委托对象
static void ProgramMothod3(MyDelegate myDelegate) {
//这里相当于调用了ProgramMothod
myDelegate();
}
static void ProgramMothod4(MyDelegate2 myDelegate, int a) {
//这里相当于调用了ProgramMothod
myDelegate(a, 200);
//Console.WriteLine($"{myDelegate}这是MyDelegate2的委托.{a}");
}
static void ProgramMothod5(int a) {
Console.WriteLine($"这是MyDelegate2的委托.{a}");
}
static string ProgramMothod6(string a, int b, double c) {
return a + b + c;
}
//如果方法参数不固定,可以将参数类型前面添加params修饰符
//params string[] strings :不管是几个参数只要类型正确都会添加到这个数组中
static string TestMethod(params string[] strings) {
string temp = "";
foreach (var item in strings) {
temp += item;
}
return temp;
}
2.声明委托 确定代理协议
delegate void MyDelegate();
delegate void MyDelegate2(int a, int b);
//委托上面要求参数类型是另外一个委托
delegate void MyDelegate3(MyDelegate myDelegate);//第二步
delegate void MyDelegate4(MyDelegate2 myDelegate, int a);
//泛型也能跟委托一起使用
delegate void MyDelegate5<T>(T a);
//返回类型和参数都设置成泛型
delegate T MyDelegate6<T, D, w>(T a, D b, w c);
Program类的 Main
static void Main(string[] args) {
//调用MyDelegate
MyDelegate m1 = new MyDelegate(ProgramMothod);
//调用m1相当于调用了ProgramMothod()
m1();
MyDelegate2 m2 = new MyDelegate2(ProgramMothod2);
//m2需传参
m2(100, 200);
Console.WriteLine("*******");
//使用ProgramMothod3这个函数
//方法的参数需要是MyDelegate的委托者
ProgramMothod3(ProgramMothod);//与下面一句代码相同
//ProgramMothod3(m1);
Console.WriteLine("*******");
MyDelegate3 m3 = new MyDelegate3(ProgramMothod3);
m3(ProgramMothod);//与下面一句代码相同
//m3(m1);
MyDelegate4 m4 = new MyDelegate4(ProgramMothod4);
//m2,a
m4(ProgramMothod2, 500);//与下面一句代码相同
//m4(m2, 500);
//委托的目的是让方法通过委托来调用,加了泛型之后就表示委托的方法里面出来的数据类型得和泛型有关才可以
MyDelegate5<int> m5 = new MyDelegate5<int>(ProgramMothod5);
m5(100);
MyDelegate6<string, int, double> m6 = new MyDelegate6<string, int, double>(ProgramMothod6);
Console.WriteLine(m6("100", 200, 300));
//因为使用了params修饰符,所以数量不定
Console.WriteLine(TestMethod("1", "2", "3", "4"));
}