如果我有一个关于封闭泛型类型的MethodInfo,是否有一种简单的方法来切换这些类型?假设我有类似Nullable.HasValue的东西。无论如何将它转换为Nullable.HasValue?我知道对于常规的泛型方法,我可以执行methodInfo.GetGenericMethod()但我看不到一种方法可以在不增加反射开销的情况下针对方法的类型执行此操作。如果我已经有了这种方法,为什么还要重新考虑呢?有趣的是,这些方法都具有相同的MetadataToken,这使得Module.ResolveMember似乎以某种方式启动正确的方法更加令人印象深刻。有没有办法用Module.ResolveMethod做到这一点?本质上,方法和类型都可以有通用参数,我可能需要切换它们。因为MethodInfo总是说它的标签是相同的,而标签说MethodInfo是该方法的最开放版本。我只需要将它转换为我的类型。编辑:更多挖掘,看起来像List.Add,我从中检索到的List.Add元数据标记实际上存在于我的模块中,而通用定义存在于不同的模块中。我真的不想在检索到成员后进行反射,因为很难确定调用的是完全相同的方法。好吧,也许我只是愚蠢,但为什么这不起作用::varmethodinfo=typeof(List).GetMethod("Add");varhandle=methodinfo.MetaDataToken;varmethodinfo2=methodinfo.Module.ResolveMethod(handle,new[]{typeof(string)},null);为什么methodInfo2说它是Add(T)而不是Add(string)?您可以使用MethodBase.GetMethodFromHandle在一行中完成此操作,但为了使用此方法,您必须传递typeof(List)而不仅仅是typeof(string)。varmethodinfo=typeof(List).GetMethod("添加");varmethodinfo2=MethodBase.GetMethodFromHandle(methodinfo.MethodHandle,typeof(List).TypeHandle);Console.WriteLine(方法信息);控制台.WriteLine(方法信息2);此链接包括上面的示例以及为什么ResolveMethod不起作用。https://www.re-motion.org/blogs/mix/archive/2009/08/12/trying-to-resolve-a-method-in-a-closed-generic-type.aspx你可以传一点更多的反射很容易完成。没有反思,你不可能神奇地做到这一点。staticvoidMain(string[]args){PropertyInfointHasValue=typeof(int?).GetProperty("HasValue");PropertyInfoboolHasValue=ChangeGenericType(intHasValue,typeof(bool));}publicstaticPropertyInfoChangeGenericType(PropertyInfoproperty,TypetargetType){Typeconstructed=property.DeclaringType;泛型类型=constructed.GetGenericTypeDefinition();输入targetConstructed=generic.MakeGenericType(new[]{targetType});返回targetConstructed.GetProperty(property.Name);当然,这只适用于具有单个类型参数的泛型类型,但如果需要可以泛化到更多类型。您必须重新考虑,因为方法不同。HasValue的唯一区别是MethodInfo.DeclaringType,而Value属性的区别是MethodInfo.ReturnType。解决了它。但最大的问题是这是一种安全的方法吗?我在这里可能做错了什么吗?以上是C#学习教程:如果我有一个封闭泛型类型的MethodInfo,有没有简单的方法来切换这些类型?如果分享的内容对你有用,需要进一步了解C#学习教程,希望你多多关注——publicstaticMethodInfoConvert(thisMethodInfomethod,paramsType[]DeclaringTypeArguments){varbaseType=method.DeclaringType.GetGenericTypeDefinition().MakeGenericType(DeclaringTypeArguments);将MethodInfo.GetMethodFromHandle(method.MethodHandle,baseType.TypeHandle)作为MethodInfo返回;}publicstaticvoidMain(String[]args){Listlist=newList();动作action=list.Add;Console.WriteLine(action.Method.Convert(typeof(string)));控制台.Read();}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
