使用类型变量调用泛型方法 [英] Calling generic method with Type variable
本文介绍了使用类型变量调用泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个通用的方法
Foo<T>
我有一个类型变量 bar
是否可以实现类似Foo
Visual Studio 需要在栏中提供类型或命名空间.
Visual Studio is expecting a type or namespace at the bar.
推荐答案
让我们假设 Foo 在类 Test 中声明,例如
Lets assume that Foo is declared in class Test such as
public class Test
{
public void Foo<T>() { ... }
}
您需要首先使用 MakeGenericMethod.然后使用反射调用它.
You need to first instantiate the method for type bar
using MakeGenericMethod. And then invoke it using reflection.
var mi = typeof(Test).GetMethod("Foo");
var fooRef = mi.MakeGenericMethod(bar);
fooRef.Invoke(new Test(), null);
这篇关于使用类型变量调用泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文