简体   繁体   English

为什么在我的属性声明“[field:NonSerialized]”中需要“field:”?

[英]Why do I need “field:” in my attribute declaration “[field:NonSerialized]”?

I can't find "field" listed as a C# keyword anywhere.我在任何地方都找不到列为 C# 关键字的“字段”。 Does anyone know the background on this?有谁知道这件事的背景?

This is necessary, for example, if you are marking an event as non-serializable.这是必要的,例如,如果您将事件标记为不可序列化。 It specifies the target that the attribute applies to.它指定属性适用的目标。

It is part of the attribute target syntax.它是属性目标语法的一部分。 From the specification :规范

attribute-target:
    field
    event
    method
    param
    property
    return
    type

See also the documentation for NonSerializedAttribute :另请参阅NonSerializedAttribute的文档:

To apply the NonSerializedAttribute class to an event, set the attribute location to field, as shown in the following C# code.要将NonSerializedAttribute类应用于事件,请将属性位置设置为 field,如以下 C# 代码所示。

[field:NonSerializedAttribute()]

public event ChangedEventHandler Changed;

The C# compiler usually has no trouble figuring out what part of a declaration the attribute applies to. C# 编译器通常可以轻松确定属性适用于声明的哪个部分。 I can think of three cases where you might use it:我可以想到您可能会使用它的三种情况:

  1. Attributes that apply to the assembly.适用于程序集的属性。 Very visible in AssemblyInfo.cs在 AssemblyInfo.cs 中非常明显
  2. An attribute applied to the return value of a P/Invoke declaration, [return:MarshalAs]应用于 P/Invoke 声明的返回值的属性,[return:MarshalAs]
  3. Having the attribute apply to the backing variable of a property or event without accessors.将该属性应用于没有访问器的属性或事件的支持变量。 Your case.你的情况。

This is meant to allow you to set NonSerialized attribute on fields, this is useful in serializing events.这是为了允许您在字段上设置 NonSerialized 属性,这在序列化事件中很有用。

For instance this would give you a compilation error例如,这会给你一个编译错误

[NonSerialized]
public event SomeEventHandler SomeEvent;

To fix this you have to use field:要解决此问题,您必须使用field:

[field:NonSerialized]
public event SomeEventHandler SomeEvent;

More on this here -- Delegates and Serialization更多关于这里 -委托和序列化

The NonSerializedAttribute is only applicable to fields, you can use it as follows: NonSerializedAttribute 仅适用于字段,您可以按如下方式使用它:

[NonSerialized]
public string myString;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM