使用Type变量调用泛型方法

Dan*_*ott 48 c# generics

我有一个通用的方法

Foo<T>
Run Code Online (Sandbox Code Playgroud)

我有一个Type变量 bar

是否有可能实现类似的目标 Foo<bar>

Visual Studio期望在栏上有一个类型或命名空间.

善良,

Vin*_*ayC 58

让我们假设Foo在类Test中声明为

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

}
Run Code Online (Sandbox Code Playgroud)

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

var mi = typeof(Test).GetMethod("Foo");
var fooRef = mi.MakeGenericMethod(bar);
fooRef.Invoke(new Test(), null);
Run Code Online (Sandbox Code Playgroud)


Eni*_*ity 31

如果我正确理解了您的问题,那么您实际上定义了以下类型:

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

public class Bar { }
Run Code Online (Sandbox Code Playgroud)

现在,假设您有一个bar如此定义的变量:

var bar = typeof(Bar);
Run Code Online (Sandbox Code Playgroud)

然后,您希望能够调用Foo<T>,替换T为您的实例变量bar.

这是如何做:

// 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() });
Run Code Online (Sandbox Code Playgroud)

请享用!

  • @`Daniel Elliot` - 是的,我知道 - 41秒后.我希望我的稍微更详细的答案会占上风,但是唉.;-) (3认同)