Delegate类简介

------------------------

命名空间:System

程序集:mscorlib(在 mscorlib.dll 中)

委托(Delegate)类是一种数据结构,通过它可引用静态方法或引用类实例及该类的实例方法。

以往的界面编程中我们应该都接触过各种类型的事件驱动(event driven)的处理模式,

在这种模式里,我们定义相应事件触发的函数。

例如:

Button1 的 Click事件,我们可以编写Button1_Click 或 Btn1Clicked等函数来做相应的驱动处理。

而事件与驱动函数的对应关系就是通过委托(Delegate)类来关联的。

其实委托(Delegate)类这种数据结构有些类似于之前C/C++中的函数指针。

Delegate类一个简单应用

------------------------

1.定义一个Delegate函数数据结构

2.定义Delegate将引用的静态方法或引用类实例及该类的实例方法

3.Delegate数据变量指向实例方法

4.通过Delegate数据变量执行实例方法

  1. A very basic example (TestClass.cs):
  2.  
  3. using System;
  4.  
  5. namespace MySample
  6. {
  7.     class TestClass
  8.     {
  9.     //1.定义一个Delegate函数数据结构
  10.         public delegate void GoDelegate();
  11.  
  12.         [STAThread]
  13.         static void Main(string[] args)
  14.         {
  15.         //3.Delegate数据变量指向实例方法
  16.             GoDelegate goDelegate = new GoDelegate( MyDelegateFunc);
  17.  
  18.         //4.通过Delegate数据变量执行实例方法
  19.             goDelegate();
  20.             return;
  21.         }
  22.  
  23.         //2.定义Delegate将引用的静态方法或引用类实例及该类的实例方法
  24.         public static void MyDelegateFunc()
  25.         {
  26.             Console.WriteLine("delegate function...");
  27.         }
  28.     }
  29. }
  30.  
  31. 编译执行结果:
  32.  
  33. # TestClass.exe
  34. delegate function...

使用Delegate类和Override实现多态的比较

-----------------------------------------------

1.使用Delegate类的时候,下面的例子可以很清楚的说明。

1.1 首先定义一个动物基类(MyAnimalDelegateClass), 基类中有显示属性的(ShowAnimalType)的public方法。

并且在ShowAnimalType方法中调用Delegate引用的实例方法

1.2 定义狮子(LionDelegateClass)和马(HorseDelegateClass)两个子类。Delegate与各自的实例方法绑定

实现不同的属性显示(ShowAnimalType)方法。

  1. ////Delegate example (TestClass.cs):
  2.  
  3. using System;
  4.  
  5. namespace MySample
  6. {
  7.    class TestClass
  8.    {
  9.       [STAThread]
  10.       static void Main(string[] args)
  11.       {
  12.       //狮子(LionDelegateClass)的属性显示(ShowAnimalType)方法调用
  13.          LionDelegateClass lionDelegate = new LionDelegateClass();
  14.          lionDelegate.ShowAnimalType("MySample");
  15.  
  16.       //马(HorseDelegateClass)的属性显示(ShowAnimalType)方法调用
  17.          HorseDelegateClass horseDelegate = new HorseDelegateClass();
  18.          horseDelegate.ShowAnimalType("MySample");
  19.       }
  20.    }
  21.  
  22.    //动物基类(MyAnimalDelegateClass)
  23.    public class MyAnimalDelegateClass
  24.    {
  25.       //Delegate数据结构定义
  26.       public delegate void DelegateFunction(string strFuncName);
  27.  
  28.       private DelegateFunction m_delegateFunction = null;
  29.  
  30.       //Delegate类型的属性
  31.       public DelegateFunction delegateFunction
  32.       {
  33.          get
  34.          {
  35.             return m_delegateFunction;
  36.          }
  37.          set
  38.          {
  39.             m_delegateFunction = value;
  40.          }
  41.       }
  42.  
  43.       //属性显示(ShowAnimalType)方法
  44.       public void ShowAnimalType(string strFuncName)
  45.       {
  46.          if (delegateFunction != null)
  47.          {
  48.             object[] args = {strFuncName};
  49.          //调用Delegate引用的实例方法
  50.             delegateFunction.DynamicInvoke(args);
  51.          }
  52.       }
  53.    }
  54.  
  55.    //狮子(LionDelegateClass)
  56.    public class LionDelegateClass:MyAnimalDelegateClass
  57.    {
  58.       public LionDelegateClass()
  59.       {
  60.          this.delegateFunction = new DelegateFunction(subFunction1);
  61.       }
  62.  
  63.       //狮子(LionDelegateClass)实例方法的实装
  64.       private void subFunction1(string strFuncName)
  65.       {
  66.          System.Console.WriteLine(
  67.             string.Format("[{0}]This is a lion....", strFuncName));
  68.       }
  69.    }
  70.  
  71.    //马(HorseDelegateClass)
  72.    public class HorseDelegateClass:MyAnimalDelegateClass
  73.    {
  74.       public HorseDelegateClass()
  75.       {
  76.          this.delegateFunction = new DelegateFunction(subFunction2);
  77.       }
  78.  
  79.       //马(HorseDelegateClass)实例方法的实装
  80.       private void subFunction2(string strFuncName)
  81.       {
  82.          System.Console.WriteLine(
  83.             string.Format("[{0}]This is a horse....", strFuncName));
  84.       }
  85.    }
  86. }
  87.  
  88. 编译执行结果:
  89.  
  90. # TestClass.exe
  91.  
  92. [MySample]This is a lion....
  93. [MySample]This is a horse....

2.使用Override实装的时候,参考下面的例子。

1.1 首先定义一个动物基类(AbstractAnimalNoDelegateClass), 基类中有显示属性的(ShowAnimalType)的public方法。

并且在ShowAnimalType方法中调用抽象方法(NoDelegateFunction)

1.2 定义狮子(LionNoDelegateClass)和马(HorseNoDelegateClass)两个子类。

子类中实装抽象方法(NoDelegateFunction)

实现不同的属性显示(ShowAnimalType)方法。

  1. ////Override example (TestClass.cs):
  2.  
  3. using System;
  4.  
  5. namespace MySample
  6. {
  7.    class TestClass
  8.    {
  9.       [STAThread]
  10.       static void Main(string[] args)
  11.       {
  12.           //狮子(LionNoDelegateClass )的属性显示(ShowAnimalType)方法调用
  13.           LionNoDelegateClass lionNoDelegate = new LionNoDelegateClass();
  14.        lionNoDelegate.ShowAnimalType("MySample");
  15.  
  16.           //马(HorseNoDelegateClass )的属性显示(ShowAnimalType)方法调用
  17.        HorseNoDelegateClass horseNoDelegate = new HorseNoDelegateClass();
  18.        horseNoDelegate.ShowAnimalType("MySample");
  19.       }
  20.    }
  21.  
  22.    //动物基类(AbstractAnimalNoDelegateClass)
  23.     public abstract class AbstractAnimalNoDelegateClass
  24.     {
  25.         public void ShowAnimalType(string strFuncName)
  26.         {
  27.             //抽象方法(NoDelegateFunction)调用
  28.             NoDelegateFunction(strFuncName);
  29.         }
  30.         //在基类中定义抽象方法(NoDelegateFunction)
  31.         protected abstract void NoDelegateFunction(string strFuncName);
  32.     }
  33.  
  34.     //狮子(LionNoDelegateClass )
  35.     public class LionNoDelegateClass:AbstractAnimalNoDelegateClass
  36.     {
  37.     // 子类中实装抽象方法(NoDelegateFunction)
  38.         protected override void NoDelegateFunction(string strFuncName)
  39.         {
  40.             System.Console.WriteLine(
  41.                 string.Format("[{0}]This is a lion....", strFuncName));
  42.         }
  43.     }
  44.  
  45.    //马(HorseNoDelegateClass )
  46.     public class HorseNoDelegateClass:AbstractAnimalNoDelegateClass
  47.     {
  48.     // 子类中实装抽象方法(NoDelegateFunction)
  49.         protected override void NoDelegateFunction(string strFuncName)
  50.         {
  51.             System.Console.WriteLine(
  52.                 string.Format("[{0}]This is a horse....", strFuncName));
  53.         }
  54.     }
  55. }
  56.  
  57. 编译执行结果:
  58.  
  59. # TestClass.exe
  60.  
  61. [MySample]This is a lion....
  62. [MySample]This is a horse....

3.比较Delegate和Override实装方式

可以看出Delegate实装方式中,相当于定义一个函数指针的成员变量。

通过把实装函数的地址赋给该成员变量,实现同样的方法,处理方式的不同。

而Override方式中,则是在父类中预先定义好接口,通过实装的不同,

来实现同样的方法,处理方式的不同。

Delegate实装方式比较灵活,适合设计不是很完善的场合,便于修改。

Override方式封装性好,相对比较安全。

MulticastDelegate 类的应用

---------------------------------

在C#中,委托(Delegate)类是多路委托,这就说可以同时指向多个处理函数,

并且可以按照委托的先后顺序,执行相应的函数。

如下例:

  1. using System;
  2.  
  3. namespace MySample
  4. {
  5.     class TestClass
  6.     {
  7.         [STAThread]
  8.         static void Main(string[] args)
  9.         {
  10.             DogDelegateClass dogDelegate = new DogDelegateClass();
  11.             dogDelegate.ShowAnimalType("MySample");
  12.  
  13.     }
  14.  
  15.     public class MyAnimalDelegateClass
  16.     {
  17.         public delegate void DelegateFunction(string strFuncName);
  18.  
  19.         private DelegateFunction m_delegateFunction = null;
  20.  
  21.         public DelegateFunction delegateFunction
  22.         {
  23.             get
  24.             {
  25.                 return m_delegateFunction;
  26.             }
  27.             set
  28.             {
  29.                 m_delegateFunction = value;
  30.             }
  31.         }
  32.  
  33.         public void ShowAnimalType(string strFuncName)
  34.         {
  35.             if (delegateFunction != null)
  36.             {
  37.                 object[] args = {strFuncName};
  38.  
  39.                 delegateFunction.DynamicInvoke(args);
  40.             }
  41.         }
  42.     }
  43.  
  44.     public class DogDelegateClass:MyAnimalDelegateClass
  45.     {
  46.         public DogDelegateClass()
  47.         {
  48.       //多路委托函数 设定
  49.             this.delegateFunction = new DelegateFunction(subFunction31);
  50.             this.delegateFunction += new DelegateFunction(subFunction32);
  51.         }
  52.   //委托函数1
  53.         private void subFunction31(string strFuncName)
  54.         {
  55.             System.Console.WriteLine(
  56.                 string.Format("[{0}]This is a dog....", strFuncName));
  57.         }
  58.   //委托函数2
  59.         private void subFunction32(string strFuncName)
  60.         {
  61.             System.Console.WriteLine(
  62.                 string.Format("[{0}]This is a nice dog....", strFuncName));
  63.         }
  64.     }
  65. }
  66.  
  67. 编译执行结果:
  68.  
  69. # TestClass.exe
  70.  
  71. [MySample]This is a dog....
  72. [MySample]This is a nice dog....

转载请表明出处!

C# Deldegate的使用的更多相关文章

随机推荐

  1. [Canvas]新版箴言钟表

    动态效果点此下载用浏览器打开观看. 本作Github地址:https://github.com/horn19782016/12MaximClock 图例: 代码: <!DOCTYPE html& ...

  2. windows 环境变量

    1.考虑下面的需求,进入cmd之后,我就想执行mysql客户端命令,而这需要转到mysql安装目录,找到mysql可执行文件,在这个目录下执行mysql命令.这样太麻烦,有没有好的解决办法? 2.使用 ...

  3. Hadoop-2.4.1学习之edits和fsimage查看器

    在hadoop中edits和fsimage是两个至关关键的文件.当中edits负责保存自最新检查点后命名空间的变化.起着日志的作用,而fsimage则保存了最新的检查点信息.这个两个文件里的内容使用普 ...

  4. Android Device Monitor工具的使用

    在最新的Android Studio3.x版本中,已经去掉了Android Device Monitor工具,但是不代表Android Device Monitor工具就不能用了,找到sdk的目录: ...

  5. 使用angular5+ionic3+sqlite创建离线app应用

    1.安装sqlite和toast插件 npm install --save @ionic-native/sqlite npm install --save @ionic-native/toast 未完 ...

  6. 微信小程序 - 自定义switch切换(示例)

    点击下载:switch示例 ,适用于表单,官方switch 说明 .

  7. tail -f 和tail -F的区别

    http://flume.apache.org/FlumeUserGuide.html flume抓取 exec 的command 官网有如下建议:

  8. 安装MySQL-python报错:_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory或者 build\lib.win-amd64-2.7\_mysql.pyd : fatal error LNK1120: 56 unresolved externa

    解决办法1: 直接下载MySQL-python-1.2.5.win-amd64/32-py2.7.exe,点击安装 此处要注意自己安装的Python和MySQL版本是64位还是32位,否则在进行安装M ...

  9. SQL基础试题

    第3章  关系数据库标准语言SQL 一.选择题 1.SQL语言是                    的语言,易学习. A.过程化    B.非过程化    C.格式化    D.导航式    答案 ...

  10. Python实践摘录

    1:中文编码问题 Python语言默认不识别UTF-8的编码字符串,所以当文件中有中文并且是以UTF-8编码时,需要在python文件头部加一行注释,指明识别utf-8编码. # coding=utf ...