代码之家  ›  专栏  ›  技术社区  ›  Daniel Elliott

使用类型变量[重复]调用泛型方法

  •  41
  • Daniel Elliott  · 技术社区  · 14 年前

    这个问题已经有了答案:

    我有一个通用方法

    Foo<T>
    

    我有一个类型变量 bar

    有没有可能达到 Foo<bar>

    Visual Studio要求在栏上有类型或命名空间。

    仁慈,

    2 回复  |  直到 6 年前
        1
  •  49
  •   VinayC    14 年前

    假设foo是在类测试中声明的,例如

    public class Test
    {
       public void Foo<T>() { ... }
    
    }
    

    您需要首先为类型实例化方法 bar 使用 MakeGenericMethod . 然后使用反射调用它。

    var mi = typeof(Test).GetMethod("Foo");
    var fooRef = mi.MakeGenericMethod(bar);
    fooRef.Invoke(new Test(), null);
    
        2
  •  29
  •   Enigmativity    14 年前

    如果我正确理解您的问题,您本质上定义了以下类型:

    public class Qaz
    {
        public void Foo<T>(T item)
        {
            Console.WriteLine(typeof(T).Name);
        }
    }
    
    public class Bar { }
    

    现在,假设你有一个变量 bar 定义如下:

    var bar = typeof(Bar);
    

    然后你想打电话给 Foo<T> 替代 T 使用实例变量 酒吧 .

    以下是如何:

    // Get the generic method `Foo`
    var fooMethod = typeof(Qaz).GetMethod("Foo");
    
    // Make the non-generic method via the `MakeGenericMethod` reflection call.
    // Yes - this is confusing Microsoft!!
    var fooOfBarMethod = fooMethod.MakeGenericMethod(new[] { bar });
    
    // Invoke the method just like a normal method.
    fooOfBarMethod.Invoke(new Qaz(), new object[] { new Bar() });
    

    享受!