非财产化的财产

问题描述 投票:50回答:3

当我写这样的代码

[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]

c# .net serialization properties
3个回答
45
投票

嗯......第一个错误说你不能那样做......来自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;

67
投票

使用简单:

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

希望它有所帮助。


1
投票

从.NET 3.0开始,您可以使用DataContract而不是Serializable。但是,使用DataContract,您需要通过使用DataMember属性标记可序列化字段来“选择加入”;或使用IgnoreDataMember“选择退出”。

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

© www.soinside.com 2019 - 2024. All rights reserved.