开发者

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

开发者 https://www.devze.com 2023-01-31 05:42 出处:网络
This question already has answers here: Why do I need "field:" in my attribute declaration "[field:No开发者_C百科nSerialized]"?
This question already has answers here: Why do I need "field:" in my attribute declaration "[field:No开发者_C百科nSerialized]"? (4 answers) Closed 8 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消