借助代码及注释了解下委托:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DelegateExample
{
  
// 声明一个委托,它的实例引用一个方法,该方法获取一个Int32参数,返回void
  // 委托本质上也是类,所以定义类的地方都可以定义委托。
internal delegate void Feedback(Int32 value); internal class DelegateDemo { private static void Counter(Int32 from, Int32 to, Feedback fb) { for (Int32 i = from; i <= to; i++) { if (fb != null) fb.Invoke(i); // fb(i); } } // 静态方法 private static void methodConsole(Int32 value) { Console.WriteLine(value); } // 实例方法 private void methodFile(Int32 value) { StreamWriter sw = new StreamWriter("status.txt", true); sw.WriteLine("Item = " + value); sw.Close(); } private static void StaticDelegate() { Console.WriteLine("Static Delegate Demo..."); Counter(1, 2, null); // 委托是一个类,每个委托都有一个构造器 // 委托对象是方法的一个包装器,使方法通过包装器来间接回调 // 此处,将 DelegateEx.methodConsole 传给 FeedBack 委托类型的构造器, // 表明 methodConsole 就是要包装的方法。 Counter(1, 2, new Feedback(DelegateDemo.methodConsole)); Console.WriteLine(); } private static void InstanceDelegate() { Console.WriteLine("Instance Delegate Demo..."); // 用委托回调实例方法 DelegateDemo d = new DelegateDemo(); Counter(1, 2, new Feedback(d.methodFile)); Console.WriteLine(); } private static void ChainDelegate(DelegateDemo d) { Console.WriteLine("Chain Delegate Demo..."); Feedback fb1 = new Feedback(methodConsole); Feedback fb2 = new Feedback(d.methodFile); Feedback fbChain = null; fbChain = (Feedback)Feedback.Combine(fbChain, fb1); // fbChain += fb1; fbChain = (Feedback)Feedback.Combine(fbChain, fb2); Counter(1, 2, fbChain); Console.WriteLine(); // fbChain -= new Feedback(methodMessBox); fbChain = (Feedback)Delegate.Remove(fbChain, new Feedback(methodConsole)); Counter(1, 2, fbChain); } public static void Excute() { StaticDelegate(); InstanceDelegate(); ChainDelegate(new DelegateDemo()); } } }

   上例是自定义的委托,也可以利用 System.Delegate 类型创建委托,代码示例如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace DelegateExample
{
    /// <summary>
    /// 定义两个委托
    /// </summary>
    internal delegate Object TwoInt32s(Int32 n1, Int32 n2);
    internal delegate Object OneString(String s);

    class Program
    {
        /// <summary>
        /// 4个回调函数
        /// </summary>
        private static Object Add(Int32 n1, Int32 n2)
        {
            return n1 + n2;
        }

        private static Object Subtract(Int32 n1, Int32 n2)
        {
            return n1 - n2;
        }

        private static Object NumChars(String s)
        {
            return s.Length;
        }

        private static Object Reverse(String s)
        {
            Char[] chars = s.ToCharArray();
            Array.Reverse(chars);
            return new String(chars);
        }
      
///
<summary> /// 了解参数由来 /// </summary> /// <param name="args">右键项目属性,选择调试选项卡,在命令行参数中设置</param> static void Main(string[] args) { #region 使用Delegate类的CreateDelegate()创建委托 if (args.Length < 2) { String fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); String usage = @"Usage:" + "{0}{1} delType methodName [Arg1] [Arg2]" + "{0} where delType must be TwoInt32s or OneString" + "{0} if delType is TwoInt32s, methodName must be Add or Subtract" + "{0} if deltype is OneString, methodName must be NumChars or Reverse" + "{0}" + "{0} Examples:" + "{0} {1} TwoInt32s Add 123,321" + "{0} {1} TwoInt32s Subtract 123,321" + "{0} {1} OneString NumChars \"Hello There \"" + "{0} {1} OneString Reverse \"Hello There \""; Console.WriteLine(usage, Environment.NewLine, fileName); Console.Read(); return; } // 将delType参数转换为一个委托类型 Type delType = Type.GetType(args[0]); if (delType == null) { Console.WriteLine("Invalid delType argument:" + args[0]); Console.Read(); return; } Delegate d; try { // 将Arg1参数转换成一个静态方法 MethodInfo mi = typeof(Program).GetMethod(args[1], BindingFlags.NonPublic | BindingFlags.Static); // 创建包含了静态方法的一个委托对象 d = Delegate.CreateDelegate(delType, mi); } catch(ArgumentException) { Console.WriteLine("Invalid methodName argument:" + args[1]); Console.Read(); return; } // 创建一个数组,其中只包含要通过委托对象传给方法的参数 Object[] callbackArgs = new Object[args.Length - 2]; if (d.GetType() == typeof(TwoInt32s)) { try { for (Int32 i = 2; i < args.Length; i++) { callbackArgs[i - 2] = Int32.Parse(args[i]); } } catch(FormatException) { Console.WriteLine("Parameters must be integers."); Console.Read(); return; } } if (d.GetType() == typeof(OneString)) { Array.Copy(args, 2, callbackArgs, 0, callbackArgs.Length); } try { // DynamicInvoke 动态调用(后期绑定)由当前委托所表示的方法 Object result = d.DynamicInvoke(callbackArgs); Console.WriteLine(d.Method.Name + " result:" + result); } catch (TargetParameterCountException) { Console.WriteLine("Incorrect number of parameters specified."); Console.Read(); return; } Console.ReadKey(); #endregion #region /* DelegateEx.Excute(); Console.Read(); */ #endregion } } }

 

posted on 2015-06-24 16:54  花爱春  阅读(193)  评论(0编辑  收藏  举报