如何将Type变量发送到通用方法?

sin*_*ici 3 c# generics generic-method

我有这样的方法,

public List<T> Test<T>()
{
    // do something.
}
Run Code Online (Sandbox Code Playgroud)

我不知道T是什么,也没有.但我的T型为TYPE.

例如:

class Person
{

}

var type = typeof(Person);
Run Code Online (Sandbox Code Playgroud)

我没有人.人在保持类型对象.

我该如何使用测试方法?

var list = Test<type>(); // It gives an error like this. I must use the type object.
Run Code Online (Sandbox Code Playgroud)

Bot*_*000 7

您可以使用以下MakeGenericMethod方法MethodInfo:

MethodInfo info = this.GetType().GetMethod("Test").MakeGenericMethod(type);
object result = info.Invoke(this, null);
Run Code Online (Sandbox Code Playgroud)

这假设您在定义的相同类型内调用方法Test.如果你从其他地方调用它,请使用typeof(ClassThatDefinesTest)而不是,而不是使用this.GetType()此类的实例this.