Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inspecting the attributes on the generated field behind a field-like event

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?

like image 820
chandmk Avatar asked Nov 05 '22 06:11

chandmk


1 Answers

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 the EventInfo (since events do not need to be backed by a field specifically - it could be proxied, or an EventHandlerList 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.

like image 115
Marc Gravell Avatar answered Nov 09 '22 12:11

Marc Gravell