我有这样的方法,
public List<T> Test<T>()
{
// do something.
}
我不知道什么是 T,也没有。但是我的类型是 T 作为 TYPE。
例如:
class Person
{
}
var type = typeof(Person);
我没有人。 Person 保持在类型对象上。
如何使用测试方法?
var list = Test<type>(); // It gives an error like this. I must use the type object.
最佳答案
您可以使用 MakeGenericMethod
方法来自 MethodInfo
:
MethodInfo info = this.GetType().GetMethod("Test").MakeGenericMethod(type);
object result = info.Invoke(this, null);
这是假设您在定义 Test
的相同类型中调用该方法。如果您从其他地方调用它,请使用 typeof(ClassThatDefinesTest)
而不是 this.GetType()
,并使用此类的实例而不是 this
.
关于c# - 如何将 Type 变量发送到通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033041/