C# delegate

C# 中的 Delegate 类似于 C++ 中函数的指针
所有的委托Delegate都派生自 System.Delegate 类。

委托的声明:

public delegate double Calculation(int x, int y);

实例化一个委托:

Calculation myCalculation = new Calculation(myMath.Average);

委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。
这里与Average方法相关

使用委托对象调用方法:

double result = myCalculation(10, 20);

结果为:15

delegate的应用:

class PrintString
   {
      static FileStream fs;
      static StreamWriter sw;


      // 委托声明
      public delegate void printString(string s);


      // 打印到控制台
      public static void WriteToScreen(string str)
      {
         Console.WriteLine("The String is: {0}", str);
      }


      // 打印到文件
      public static void WriteToFile(string s)
      {
         fs = new FileStream("c:\\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }


      // 该方法把委托作为参数,并使用它调用方法
      public static void sendString(printString ps)
      {
         ps("Hello World");
      }


      static void Main(string[] args)
      {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }

sendString(ps1)会在控制台上打印出:The String is: Hello World

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • C#的Delegate 很像C++中的函数指针,首先声明一个Delegate的对象。 SetValue就像使C++...
    若水生花啊啊啊阅读 409评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,908评论 18 139
  • 一个袖筒里装了吵 另一个盛了闹 白日里赶路的人多善良 一双手笼在袖筒里 不吵不闹 只用脚丈量 异乡到故乡的云 只用...
    大朋小雷阅读 304评论 5 3
  • 现在翻看你的朋友圈,估计看了不到三分钟你就会看到一个微商朋友。也许有的朋友说,我的朋友圈没有,因为我屏蔽了。也有的...
    紫色风_c499阅读 231评论 0 0
  • 12月2日-3日在天津参加了DISC双证班,对我来说它是一场很神奇的旅程。和小组内的伙伴交流时我就说:参加双证班,...
    传习录每日60秒阅读 362评论 4 3