【问题标题】:How can I call generic method unknowing instance object type如何调用不知道实例对象类型的泛型方法
【发布时间】:2026-02-12 18:50:02
【问题描述】:
使用此代码:
World w = new World();
var data = GetData<World>(w);
如果我通过反射得到w,这可以是World、Ambient、Domention等类型。
我怎样才能得到GetData???
我只有实例对象:
var data = GetData<???>(w);
【问题讨论】:
标签:
c#
generics
object
instance
【解决方案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】:
你不需要写部分。如果未声明类型,C# 隐式决定泛型方法中参数的类型;就去吧:
var data = GetData(w);
这是一个示例;
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;
}
}
你可以这样称呼它;
IM a = new M();
SomeGenericClass s = new SomeGenericClass();
s.GetData(a);