TypeBuilder 上的 TypeBuilder.GetMethod
TypeBuilder.GetMethod
允许您获取由 TypeBuilder
关闭的泛型类型的方法,因此它可以让我执行以下操作:
TypeBuilder tb = ....
// this would throw a NotSupportedException :
// var ec = typeof(EqualityComparer<>).
// MakeGenericType(tb).GetMethod("get_Default");
// this works:
var ec = TypeBuilder.GetMethod(tb, typeof(EqualityComparer<>).
GetMethod("get_Default");
什么不起作用(而且我不能弄清楚如何让它发挥作用)是这样的:
Type collectionOf = typeof(ICollection<>).MakeGenericType(tb);
// throws: 'Type must be a type provided by the runtime.
// Parameter name: types'
var colEc = TypeBuilder.GetMethod(collectionOf, typeof(EqualityComparer<>).
GetMethod("get_Default");
// throws NotSupportedException
colEc = typeof(EqualityComparer<>).MakeGenericType(collectionOf).
GetMethod("get_Default");
有人知道答案吗(我希望是 42)...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我并不完全清楚你想要做什么(看起来你缺少一些括号,以及其他问题),但是如果你试图获取
的>.get_Default
,这对我有用:MethodInfo
EqualityComparerIt's not completely clear to me what you're trying to do (it looks like you're missing some parentheses, among other issues), but if you're trying to get a
MethodInfo
forEqualityComparer<ICollection<YourType>>.get_Default
, this works for me:正如前面所说,您无法对尚未创建的类型进行反射。
您需要跟踪这些方法,或者确保您有一个从调用
TypeBuilder.CreaterType()
返回的运行时类型。TypeBuilder
“方便地”会为您跟踪创建的运行时类型(如果已经创建)。这适用于
Reflection.Emit
类型中的几乎所有反射操作,而不仅仅是TypeBuilder
。更新:
我之前没有注意到
TypeBuilder.GetMethod
,所以我上面可能是错的。会详细了解的。 :)更新 2:可能的解决方案
以下工作有效吗?
应该测试:(
Like said earlier, you cannot do reflection on types that have not been created yet.
You need to either keep track of the methods, or ensure that you have a runtime type that is returned from called
TypeBuilder.CreaterType()
.TypeBuilder
'conveniently' does keep track of the created runtime type for you if it has already been created.This goes for almost every reflection operation in
Reflection.Emit
types, not justTypeBuilder
.Update:
I have not noticed
TypeBuilder.GetMethod
before, so I am probably wrong above. Will find out the detail. :)Update 2: Possible solution
Does the following work?
Should be testing :(