문제

I have a method like this,

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

I don't know what is T and dont have. But I have type of T as TYPE.

for example:

class Person
{

}

var type = typeof(Person);

I don't have Person. Person is keeping at the type object.

How can I use the test method ?

var list = Test<type>(); // It gives an error like this. I must use the type object.
도움이 되었습니까?

해결책

You can use the MakeGenericMethod method from MethodInfo:

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

This is assuming you call the method inside the same type that defines Test. If you call it from somewhere else, use typeof(ClassThatDefinesTest) instead of this.GetType(), and the instance of this class instead of this.

다른 팁

If typeof(T) is all you really needed, then you can refactor it to:

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

And call it like:

Test(type);

If this won't work for you, I recommend Botz3000's solution using MakeGenericMethod.

You could expose both Test<T>() and Test(Type) and then have one call the other, (either with MakeGenericMethod or typeof(T)) depending on whether you need the static type or simply the runtime type. That way your callers don't need to know which of the two you need.

You have pass the Class name to it. Please refer to the following MSDN,

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

As said @Botz3000 you can use MakeGenericMethod() method. But another solution could be use the dynamic keyword and the CreateInstance() method from Activator class:

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

You call it like this:

Test<Person>();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top