使用委托來做一些事情,大致思路是:
1、定義聲明一個委托,規(guī)定輸入?yún)?shù)和輸出類型。2、寫幾個符合委托定義的方法。3、把方法列表賦值給委托4、執(zhí)行委托
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)){
新聞熱點(diǎn)
疑難解答