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

时间:2012-06-14 12:25:45

标签: c# generic-method generics

我有这样的方法,

public List<T> Test<T>()
{
    // do something.
}

我不知道什么是T而且没有。但我的T类型为TYPE。

例如:

class Person
{

}

var type = typeof(Person);

我没有人。人保持着类型对象。

我如何使用测试方法?

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

5 个答案:

答案 0 :(得分:7)

您可以使用MakeGenericMethod中的MethodInfo方法:

MethodInfo info = this.GetType().GetMethod("Test").MakeGenericMethod(type);
object result = info.Invoke(this, null);

这假设您在定义Test的同一类型中调用方法。如果您从其他地方拨打电话,请使用typeof(ClassThatDefinesTest)代替this.GetType(),并使用此类的实例代替this

答案 1 :(得分:1)

如果您真正需要typeof(T),那么您可以将其重构为:

public void Test(Type t)
{
    // do something.
}

并称之为:

Test(type);

如果这对您不起作用,我推荐使用MakeGenericMethod的Botz3000解决方案。

您可以同时公开Test<T>()Test(Type),然后另一个调用(MakeGenericMethodtypeof(T)),具体取决于您是否需要静态类型或只是运行时类型。这样你的来电者就不需要知道你需要哪两个了。

答案 2 :(得分:0)

您已将类名传递给它。请参阅以下MSDN,

http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.100).aspx

答案 3 :(得分:0)

如上所述 @ Botz3000 ,您可以使用MakeGenericMethod()方法。但另一种解决方案可能是使用dynamic关键字和CreateInstance()类中的Activator方法:

public void Test(Type type)
{
    dynamic myVariable = Activator.CreateInstance(type);          
    // do something, like use myVariable and call a method: myVariable.MyMethod(); ...
}

答案 4 :(得分:-1)

你这样称呼它:

Test<Person>();