使用委托来做一些事情,大致思路是:
1、定义声明一个委托,规定输入参数和输出类型。2、写几个符合委托定义的方法。3、把方法列表赋值给委托4、执行委托
internal delegate int MyDelegate();class PRogram{static void Main(string[] args){MyDelegate d = ReturnOne;d += ReturnTwo;foreach (int i in GetAllReturnVals(d)){Console.WriteLine(i);}Console.ReadKey();}static IEnumerable<int> GetAllReturnVals(MyDelegate myDelegate){foreach (MyDelegate del in myDelegate.GetInvocationList()){yield return del();}}static int ReturnOne(){return 1;}static int ReturnTwo(){return 2;}}
以上,委托的返回类型是int,如果让返回类型是泛型呢?只要让以上的GetAllReturnVals方法针对泛型就可以了。
internal delegate T MyDelegate<T>();class Program{static void Main(string[] args){MyDelegate<int> d = ReturnOne;d += ReturnTwo;foreach (int i in GetAllReturnVals(d)){
新闻热点
疑难解答