如何在不知道实例对象类型的情况下调用通用方法 [英] How can I call generic method unknowing instance object type

查看:84
本文介绍了如何在不知道实例对象类型的情况下调用通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

World w = new World();
var data = GetData<World>(w);

如果我用反射得到w,并且可以是WorldAmbientDomention等类型.

If I get w with reflection and this can be of type World, Ambient, Domention, etc.

如何获取GetData ???

我只有实例对象:

var data = GetData<???>(w);

推荐答案

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});

这篇关于如何在不知道实例对象类型的情况下调用通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆