美文网首页
C# delegate

C# delegate

作者: Tommmmm | 来源:发表于2018-05-24 10:36 被阅读0次

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#委托

    C#中的delegate 在c#中,event与delegate是两个非常重要的概念。因为在Windows应用程序...

  • C# 委托

    C#委托 C#中的委托(Delegate)类似于C或C++中函数的指针。委托(Delegate)是存有对某个方法的...

  • C# 高级语言总结

    后续 1 C# 委托 委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 ...

  • C# Unity 委托

    文档:Delegat 一.解释下delegate: 我们平时使用的delegate,是关键字 C#编译器,它先自动...

  • C# delegate

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

  • C# 委托(Delegate)

    C# 中的委托(Delegate)类似于 C 或 C++ 中的函数指针。委托(Delegate) 是存有对某个方法...

  • C#委托Delegate和事件Event实战应用

    一、委托的概念 C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate)是...

  • 19-委托

    C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。 委托(Delegate) 是存有对某个方...

  • 编写简单的事件机制实例

    C#事件机制 public delegate void SalaryCompute(); //声明一个代理类...

  • C# Delegate

    C#的Delegate 很像C++中的函数指针,首先声明一个Delegate的对象。 SetValue就像使C++...

网友评论

      本文标题:C# delegate

      本文链接:https://www.haomeiwen.com/subject/tpmjjftx.html