using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tryDelegate { public delegate int AddDelegate(int a, int b); //定位委托类型 class Program { public static int add(int a, int b) { Console.WriteLine($"a:{a}, b:{b}"); return a + b; } static void Main(string[] args) { MyDelegate myDelegate = new MyDelegate(); //用法1,指定委托(该方法主要用于指向非特定功能的方法,如:猫,狗叫声,同样是叫,不过输出不一样。) myDelegate.addDelegate = add; myDelegate.addDelegate(1, 2); //用法2:指定事件(该方法主要用于回调事件,在被调用的类里面,有相关方法需要通知到调用方时可以用。) myDelegate.addDelegateEvent += add; myDelegate.addDelegateEvent += add; myDelegate.DoSomething(); Console.ReadKey(); } class MyDelegate { public AddDelegate addDelegate;//定义委托 public event AddDelegate addDelegateEvent; //定义事件 public void DoSomething() { if (addDelegateEvent != null) { addDelegateEvent(2, 3); } } } } }
c# 委托 和 事件
猜你喜欢
转载自www.cnblogs.com/bug01/p/11211998.html
今日推荐
周排行