属性上的非序列化

本文关键字:序列化 属性 | 更新日期: 2023-09-27 18:10:47

当我写这样的代码

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

我得到以下错误:

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


如果我写

[field: NonSerialized]

我得到以下警告

'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.


如果我写

[property: NonSerialized]

我得到以下错误(再次):

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


我如何在一个属性上使用[NonSerialized] ?

属性上的非序列化

简单用法:

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

嗯…第一个错误说你不能那样做……从http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx

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

我建议使用后备字段

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

从c# 7.3开始,您可以将属性附加到自动实现属性的后台字段。

因此,如果您将项目的语言更新为c# 7.3,下面应该可以工作:

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

对于使用JSON而不是XML的用户,可以在properties中使用[JsonIgnore]属性:

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

可在Newtonsoft。Json和System.Text.Json. NET Core 3.0).

从。net 3.0开始,你可以使用DataContract来代替Serializable。然而,对于DataContract,你需要通过用DataMember属性标记可序列化字段来"选择加入";或使用ignoredatammember "选择退出"

选择加入与选择退出的主要区别在于默认情况下选择退出只序列化公共成员,而选择加入只序列化标记的成员(无论保护级别如何)。