[英]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:我可以想到您可能会使用它的三种情况:
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.