如何在 C# 中声明和实例化委托?


C# 委托与 C 或 C++ 中指向函数类似。委托是一个引用类型变量,持有一个方法的引用。引用可以在运行时被改变。

声明委托的语法 −

delegate <return type> <delegate-name> <parameter list>

现在,让我们看看如何实例化 C# 中的委托。

声明委托类型后,必须使用 new 关键字创建一个委托对象,并将其与一个特定的方法关联。创建委托时,传递给 new 表达式的参数的写法类似于方法调用,但是没有方法的参数。

public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

以下是 C# 中声明和实例化委托的一个示例 −

示例

 实时演示

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl {

   class TestDelegate {
      static int num = 10;

      public static int AddNum(int p) {
         num += p;
         return num;
      }

      public static int MultNum(int q) {
         num *= q;
         return num;
      }

      public static int getNum() {
         return num;
      }

      static void Main(string[] args) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);

         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

输出

Value of Num: 35
Value of Num: 175

更新于:20-6 月-2020

300 次浏览

开启你的 职业

通过完成本课程获得证书

开始
广告