zoukankan      html  css  js  c++  java
  • 【C# 反射泛型】

    C# 反射泛型

    摘自:http://www.itwis.com/html/net/c/20110411/10175.html

    C#泛型反射和普通反射的区别,泛型反射和普通反射的区别就是泛型参数的处理上
     
    先看一个简单的例子。
     
    class Class1<T>
    {
      public void Test(T t)
      {
        Console.WriteLine(t);
      }
    }
     
    要利用反射动态创建该类型实例,并调用 Test 方法,我们可以使用如下方法
     
    Type type = typeof(Class1<int>);
    object o = Activator.CreateInstance(type);
    type.InvokeMember("Test", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, new object[] { 123 });
     
    但如果泛型参数是未定的,我们该如何处理呢?其实 Type 已经增加了类似的处理机制。
     
    static void InvokeTest(Type t, params object[] args)
    {
      Type type = typeof(Class1<>);
      type = type.MakeGenericType(t);
      object o = Activator.CreateInstance(type);
      type.InvokeMember("Test", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, args);
    }
     
    另外一种情况就是泛型方法,
    class Class1
    {
      public void Test<T>(T t)
      {
        Console.WriteLine(t);
      }
    }
     
    方法类似,只不过这回使用的是 MethodInfo.MakeGenericMethod()
     
    static void InvokeTest(Type t, params object[] args)
    {
      Type type = typeof(Class1);
      object o = Activator.CreateInstance(type);
      MethodInfo method = type.GetMethod("Test", BindingFlags.Instance | BindingFlags.Public);
     
      method = method.MakeGenericMethod(t);
      method.Invoke(o, args);
    }

    当然还有实例化一个泛型

    例如有GenericType<M,N>

    Type genericType = typeof(GenericType<>);

    Type[] templateTypeSet = new[] { typeof(string), typeof(int) };

    Type implementType = genericType.MakeGenericType( templateTypeSet );

    这样 implementType类型就是赋予了string,int的泛型类了

  • 相关阅读:
    HDU
    HDU
    HDU
    HDU
    POJ
    POJ
    POJ
    hdu-4745 Two Rabbits
    蓝桥杯历年试题 小朋友排队
    蓝桥杯历年试题 矩阵翻硬币
  • 原文地址:https://www.cnblogs.com/easy5weikai/p/3790589.html
Copyright © 2011-2022 走看看