How can I call generic method unknowing instance object type

孤街浪徒 提交于 2020-04-05 05:24:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!