C# 中的泛型委托是什么?


使用泛型委托,你不必定义委托语句。它们是在 System 命名空间中定义的。

你可以使用类型参数定义一个泛型委托。例如 −

delegate T myDelegete<T>(T n);

示例

以下是一个展示如何在 C# 中创建泛型委托的示例 −

using System;
using System.Collections.Generic;

delegate T myDelegete<T>(T n);
namespace GenericDelegateAppl {
   class TestDelegate {
      static int num = 5;

      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(50);
         Console.WriteLine("Value of Num: {0}", getNum());

         nc2(10);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

更新于: 20-Jun-2020

905 人次观看

开启你的 职业生涯

通过完成课程获取认证

开始学习
广告
© . All rights reserved.