如何过滤作为类事件的底层实现的 FieldInfo?
我想获取类的所有字段,而不获取类事件的底层实现。 type.GetFields(BindingFlags...) 返回事件字段的裸体委托。有谁知道如何过滤掉它们?
I want to get all the fields of a class without getting the underlying implementations of the class event.
type.GetFields(BindingFlags...) returns the nuderlying delegate for event fields. Does anyone knows how to filter them out ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.NET 中的事件生成一个与事件具有相同类型的字段。此外,它们还生成两个方法(adder 和remover,它们与带有前缀“add_”和“remove_”的字段同名)。
为了过滤事件支持字段,您可以删除与事件同名的字段。您可以确保不会定义与事件同名的字段,因为如果使用相同名称定义另一个成员,编译器将导致编译失败。
例如:
用法示例:
编辑: 添加了对 VB 和 C# 的支持
此代码将适用于自动生成的事件(自定义加法器或删除器将破坏代码)。这也是一个有风险的代码,它对 adder 方法的生成和编译方式做出了一些假设。我将此代码发布为“学术”信息,我不会在生产代码中使用它。
这里所做的假设是,adder 方法主体中的字节 3-6 是事件的后备字段的标记。我真的希望有人能为这个问题发布一个优雅且安全的解决方案:)
Events in .NET generate a field with the same and type as the event. In addition they generates two methods (adder and remover, which have the same name as the field with prefixes 'add_' and 'remove_').
In order to filter event backing fields you can remove fields with same name as events. You can be sure no field will be defined with same name as event since the compiler will fail the compilation if another member is defined with the same name.
For example:
Usage example:
EDIT: added support to work with VB and C#
This code will work on auto generated events (custom adder or remover will break the code). This is also a risky code, it makes some assumptions on the way adder method is generated and compiles. I am posting this code as "Academic" information, I wouldn't use it in production code.
The assumption made here is that the bytes 3-6 in the adder method body are the token of the backing field of the event. I really hope someone will post an elegant and safe solution to this problem :)