如果我有一个封闭泛型类型一个MethodInfo的是有一个简单的方法来切换那些类型? [英] If I have a MethodInfo on a closed generic Type is there an easy way to switch those types?
问题描述
让我们说,我有MethodInfo的东西像可空< INT> .HasValue
。
反正是有其转换为可空<串> .HasValue
Let's say that I have the methodInfo for something like Nullable<int>.HasValue
.
Is there anyway to convert it to Nullable<string>.HasValue
?
我知道了定期泛型方法我可以做 methodInfo.GetGenericMethod()
,但我没有看到一个办法做到这一点从方法的类型,没有做更多的思考开销。如果我已经有方法,为什么我要再次体现?
I know for a regular generic method I can do methodInfo.GetGenericMethod()
but I don't see a way to do it for the type from the method, without doing more reflection overhead. If I already have the method why do I have to reflect again?
有趣的是这些方法都具有相同的 MetadataToken
,这使得它更令人印象深刻,不知怎的,Module.ResolveMember似乎右拉一出。
Interestingly enough the methods all have the same MetadataToken
, which makes it more impressive that somehow Module.ResolveMember seems to pull the right one out.
有没有办法用 Module.ResolveMethod
来做到这一点?本质上,该方法和类型可以都具有通用的参数,以及我可能需要切换。由于MethodInfo的总是说,它的令牌是相同的令牌代表的MethodInfo是最开放的版本的方法。我只是需要好歹它转换为我喜欢的类型。
Is there any way to do this with the Module.ResolveMethod
? Essentially, the method and type may both have generic parameters, and I may need to switch them. Since the MethodInfo always says its token is the same and the token represents the MethodInfo is the most open version of the method. I just need someway for it to be converted to my type.
编辑:
更多的挖掘,似乎这样的事情名单,LT ; T>。新增
,列表< INT>。新增
的元数据标记我从中获取实际生活我的模块中,而通用定义生活在不同的模块。
More digging, it appears that for something like List<T>.Add
, List<int>.Add
metadata token from which i retrieve is actually living in my module, while the generic definition lives in a different module.
我真的不希望,一旦我找回员有一次,因为它是非常难以解决被调用的确切同样的方法做反思。
I really don't want to do reflection once I retrieve the member once, as it's very difficult to resolve the exact same method being invoked.
好吧,也许我只是愚蠢,但到底为什么这是否不工作:
Okay maybe I'm just stupid, but why exactly does this not work::
var methodinfo = typeof(List<int>).GetMethod("Add");
var handle = methodinfo.MetaDataToken;
var methodinfo2 = methodinfo.Module.ResolveMethod(handle,new []{typeof(string)},null);
为什么methodInfo2说,这是添加(T)
,而不是添加(字符串)
?
推荐答案
可以做一个符合 MethodBase.GetMethodFromHandle
,但为了使用这种方法,你就必须通过的typeof(名单<串>)
而不仅仅是 typeof运算(字符串)
。
You can do it in one line with MethodBase.GetMethodFromHandle
but in order to use this method you'll have to pass typeof(List<string>)
not just typeof(string)
.
var methodinfo = typeof(List<int>).GetMethod("Add");
var methodinfo2 = MethodBase.GetMethodFromHandle(methodinfo.MethodHandle,
typeof (List<string>).TypeHandle);
Console.WriteLine(methodinfo);
Console.WriteLine(methodinfo2);
这链路包括上面的示例,为什么 ResolveMethod $的exlpanation C $ C>不起作用。
This link includes the above sample and an exlpanation of why ResolveMethod
doesn't work.
的https://www.re-motion.org/blogs/mix/archive/2009/08/12/试图对解决同一个法-IN-A-封闭仿制type.aspx
这篇关于如果我有一个封闭泛型类型一个MethodInfo的是有一个简单的方法来切换那些类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!