Difference between [field: NonSerialized] and [NonSerialized] in C #

What's the difference between

[field: NonSerialized] public event EventHandler<SelectedPageChangeEventArgs> SelectedPageChanged; 

and

 [NonSerialized] public event EventHandler<SelectedPageChangeEventArgs> SelectedPageChanged; 
+4
source share
3 answers

field: prefix is ​​used to apply attributes to fields, just like method: used with methods.

In your given code, only the first will be compiled, and the other (without the field: prefix will not.

The reason you need to add the field: prefix with the NonSerialized attribute is because it is limited to fields only:

[from metadata]

 [AttributeUsage(AttributeTargets.Field, Inherited = false)] [ComVisible(true)] public sealed class NonSerializedAttribute : Attribute { public NonSerializedAttribute(); } 
+1
source

Indicates an event, and another is a support field with an attribute.

Attribute Objectives

The attribute specified in the event declaration, which omits the accessor declarations, can be applied to the declared event, to the corresponding field (if the event is not abstract), or to related methods of adding and removing. In the absence of an attribute-attribute-attribute attribute is applied to the event declaration. The target attribute, equal to the event, indicates that the attribute applies to the event; target-target equal to the field indicates that the attribute is applied to the field; and the target attribute equal to the method indicates that the attribute applies to the methods.

http://en.csharp-online.net/ECMA-334:_24.2_Attribute_specification

+1
source

In your particular case there is no difference. You get into the topic of attribute goals . In certain scenarios where there is some ambiguity, goals will come into play. Link does a good job explaining this.

+1
source

Source: https://habr.com/ru/post/1332221/


All Articles