我有一个通用的方法
Foo<T>
我有一个Type变量bar
是否可以实现Foo<bar>
Visual Studio希望栏中有一个类型或命名空间。
善,
丹
答案 0 :(得分:50)
让我们假设Foo在类Test中声明,例如
public class Test
{
public void Foo<T>() { ... }
}
您需要首先使用MakeGenericMethod实例化bar
类型的方法。然后使用反射调用它。
var mi = typeof(Test).GetMethod("Foo");
var fooRef = mi.MakeGenericMethod(bar);
fooRef.Invoke(new Test(), null);
答案 1 :(得分:30)
如果我理解你的问题,实际上你定义了以下类型:
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
,取代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() });
享受!