检查类字段事件背后生成字段的属性
鉴于以下类定义
public class MyClass
{
[System.ComponentModel.Browsable(true)]
[field:NonSerialized]
public event EventHandler MyEvent;
}
在我的代码中的其他地方,我希望看到事件的属性。
var attributes = typeof(MyClass)
.GetEvents()
.SelectMany(n => n.GetCustomAttributes(true));
但我在该属性集合中只看到 BrowsableAttribute
。
如何获取 field:NonSerialized
属性信息?
Given the following class definition
public class MyClass
{
[System.ComponentModel.Browsable(true)]
[field:NonSerialized]
public event EventHandler MyEvent;
}
Somewhere else in my code, I would like see the attributes on the event.
var attributes = typeof(MyClass)
.GetEvents()
.SelectMany(n => n.GetCustomAttributes(true));
But I am seeing only BrowsableAttribute
in that attributes collection.
How can I get the field:NonSerialized
attribute info?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
field:
语法意味着该属性附加到编译器生成的字段(以支持该字段)。您永远不会知道该字段的名称,因为它是一个实现细节,并且它不是EventInfo
的一部分(因为事件不需要专门由字段支持 - 它可以是代理,或EventHandlerList
等)。如果您需要该级别的信息,您可能需要手动实现该事件(而不是如图所示的“类似字段的事件”),但是;事实上,您很少需要知道这一点。 实际上只有
BinaryFormatter
等人才需要此信息,以表示“放手”。另一种方法是使用 GetFields(),但同样;不存在将字段映射到事件的可靠方法。
The
field:
syntax means that the attribute is attached to the field that is generated by the compiler (to support this field). You never get to know the name of this field, since it is an implementation detail, and it is not part of theEventInfo
(since events do not need to be backed by a field specifically - it could be proxied, or anEventHandlerList
etc).If you need that level of information, you might want to implement the event manually (rather than a "field-like event", as depicted), but; in reality it is rare you would need to know this. This information is really only needed by
BinaryFormatter
et al, to say "hands off".Another approach would be to use
GetFields()
, but again; no robust way of mapping fields to events exists.