问题
With this code:
World w = new World();
var data = GetData<World>(w);
If I get w
with reflection and this can be of type World
, Ambient
, Domention
, etc.
How can I get GetData
???
I only have the instance object:
var data = GetData<???>(w);
回答1:
var type = <The type where GetData method is defined>;
var genericType = typeof(w);
var methodInfo = type.GetMethod("GetData");
var genericMethodInfo = methodInfo.MakeGenericMethod(genericType);
//instance or null : if the class where GetData is defined is static, you can put null : else you need an instance of this class.
var data = genericMethodInfo.Invoke(<instance or null>, new[]{w});
回答2:
You do not need to write section. C# implicity decides the type of the parameter in a generic method if type is not declared; just go with:
var data = GetData(w);
Here is a sample;
public interface IM
{
}
public class M : IM
{
}
public class N : IM
{
}
public class SomeGenericClass
{
public T GetData<T>(T instance) where T : IM
{
return instance;
}
}
And you may call it like;
IM a = new M();
SomeGenericClass s = new SomeGenericClass();
s.GetData(a);
来源:https://stackoverflow.com/questions/10700610/how-can-i-call-generic-method-unknowing-instance-object-type