委托的使用2

委托的使用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"));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值