Difference between [field: NonSerialized] and [NonSerialized] in C# [duplicate]
What is the difference between
[field: NonSerialized]
public event EventHandler<SelectedPageChangeEventArgs> SelectedPageChanged;
and
[NonSerialized]
public event EventHandler<SelectedPageChangeEventArgs> SelectedPageChanged;
field:
prefix is used to apply attributes on fields just like method:
is used with methods.
In your given code, only the first one will compile and other one (without field:
prefix) will not.
The reason you need to add field:
prefix with NonSerialized
attribute is because it is restricted to be used on fields only:
[from metadata]
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
[ComVisible(true)]
public sealed class NonSerializedAttribute : Attribute
{
public NonSerializedAttribute();
}
One marks the event and the other the backing field with the attribute.
Attribute Targets
An attribute specified on an event declaration that omits event-accessor-declarations can apply to the event being declared, to the associated field (if the event is not abstract), or to the associated add and remove methods. In the absence of an attribute-target-specifier, the attribute applies to the event declaration. An attribute-target equal to event indicates that the attribute applies to the event; an attribute-target equal to field indicates that the attribute applies to the field; and an attribute-target equal to method indicates that the attribute applies to the methods.
http://en.csharp-online.net/ECMA-334:_24.2_Attribute_specification
In your particular case, there is no difference. You are getting into the topic of attribute targets. In certain scenarios where there is some ambiguity, targets would come into play. The link does a good job explaining this.
精彩评论