简体   繁体   English

属性上的非序列化

[英]NonSerialized on property

When I write code like this当我写这样的代码时

[XmlIgnore]
[NonSerialized]
public List<string> paramFiles { get; set; }

I get the following error:我收到以下错误:

Attribute 'NonSerialized' is not valid on this declaration type.
It is only valid on 'field' declarations.


If I write如果我写

[field: NonSerialized]

I get the following warning我收到以下警告

'field' is not a valid attribute location for this declaration.
Valid attribute locations for this declaration are 'property'.
All attributes in this block will be ignored.


If I write如果我写

[property: NonSerialized]

I get the following error (again):我收到以下错误(再次):

Attribute 'NonSerialized' is not valid on this declaration type.
It is only valid on 'field' declarations.


How can I use [NonSerialized] on a property?如何在属性上使用[NonSerialized]

Simple use:简单使用:

[XmlIgnore]
[ScriptIgnore]
public List<string> paramFiles { get; set; }

Hopefully, it helps.希望它有所帮助。

Well... the first error says that you can't do that... from http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx嗯......第一个错误说你不能这样做......来自http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx

 [AttributeUsageAttribute(AttributeTargets.Field, Inherited = false)]
 [ComVisibleAttribute(true)]
 public sealed class NonSerializedAttribute : Attribute

I suggest using backing field我建议使用支持字段

 public List<string> paramFiles { get { return list;}  set { list = value; } }
 [NonSerialized]
 private List<string> list;

From C# 7.3 you may attach attributes to the backing field of auto-implemented properties.从 C# 7.3 开始,您可以将属性附加到自动实现的属性的支持字段。

Hence the following should work if you update your project's language to C# 7.3:因此,如果您将项目的语言更新为 C# 7.3,以下内容应该有效:

[field: NonSerialized]
public List<string> paramFiles { get; set; }

For those using JSON instead of XML you can use the [JsonIgnore] attribute on properties:对于那些使用 JSON 而不是 XML 的人,您可以在属性上使用[JsonIgnore]属性:

[JsonIgnore]
public List<string> paramFiles { get; set; }

Available in both Newtonsoft.Json and System.Text.Json (.NET Core 3.0) .Newtonsoft.JsonSystem.Text.Json (.NET Core 3.0) 中可用。

As of .NET 3.0, you can use DataContract instead of Serializable.从 .NET 3.0 开始,您可以使用DataContract而不是 Serializable。 With the DataContract though, you will need to either "opt-in" by marking the serializable fields with the DataMember attribute;但是,对于 DataContract,您需要通过使用DataMember属性标记可序列化字段来“选择加入”; or "opt-out" using the IgnoreDataMember .或“选择退出”使用IgnoreDataMember

The main difference between opt-in vs opt-out is that opt-out by default will only serialize public members, while opt-in will only serialize the marked members (regardless of protection level). opt-in 与 opt-out 的主要区别在于,默认情况下,opt-out 只会序列化公共成员,而 opt-in 只会序列化标记的成员(无论保护级别如何)。

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

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