实例讲解C# 泛型(Generic)

2020-06-29 19:00:50刘景俊

当上面的代码被编译和执行时,它会产生下列结果:

Int values before calling swap:
a = 10, b = 20
Char values before calling swap:
c = I, d = V
Int values after calling swap:
a = 20, b = 10
Char values after calling swap:
c = V, d = I

泛型(Generic)委托

您可以通过类型参数定义泛型委托。例如:

delegate T NumberChanger<T>(T n);

下面的实例演示了委托的使用:

using System;
using System.Collections.Generic;

delegate T NumberChanger<T>(T n);
namespace GenericDelegateAppl
{
  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)
    {
      // 创建委托实例
      NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
      NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
      // 使用委托对象调用方法
      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

以上就是实例讲解C# 泛型(Generic)的详细内容,更多关于C# 泛型(Generic)的资料请关注易采站长站其它相关文章!