[英]Why doesn't [NonSerialized] work on autoimplemented properties?
[Serializable]
class MyClass
{
[NonSerialized] int Foo { get; set; } // error
[NonSerialized] int bar; // ok
}
为什么不允许这样做?
我知道诸如以下的解决方法
问题特别是为什么 [NonSerialized]不允许在属性上使用,而在字段上允许。
属性实际上是方法,它们不会通过二进制序列化过程进行序列化。 是被序列化的字段。 因此,仅在字段上指定NonSerialized
才有意义。
我认为这是一种精细控制的情况,需要您付出更多的努力。 换句话说,默认情况下,自动属性将具有可序列化的后备字段。 如果要使用默认值以外的任何其他内容,则不能使用自动属性。
我以为对属性使用[field:NonSerialized]
可能有效,但无效。 C#规范未明确指出支持字段的可序列化性,但确实包含此内容(10.7.3):
The following example:
public class Point {
public int X { get; set; } // automatically implemented
public int Y { get; set; } // automatically implemented
}
is equivalent to the following declaration:
public class Point {
private int x;
private int y;
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
}
因此,支持字段是可序列化的(默认值)。
如果使用的是WCF,则可能需要查看IgnoreDataMemberAttribute
。 这适用于自动属性。
即使您没有将所有其他成员都标记为DataMember
(我总是觉得很痛苦)并且使用DataContract
将该类标记为有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.