简体   繁体   English

为什么[NonSerialized]在自动实现的属性上不起作用?

[英]Why doesn't [NonSerialized] work on autoimplemented properties?

[Serializable]
class MyClass
{
    [NonSerialized] int Foo { get; set; } // error
    [NonSerialized] int bar; // ok
}

Why is this disallowed? 为什么不允许这样做?

I know about the workarounds such as 我知道诸如以下的解决方法

  • implementing ISerializable 实现ISerializable
  • switching to XmlSerializer/XmlIgnore 切换到XmlSerializer / XmlIgnore
  • switching to a manually-implemented property 切换到手动执行的属性

The question is specifically why is [NonSerialized] disallowed on properies, yet allowed on fields. 问题特别是为什么 [NonSerialized]不允许在属性上使用,而在字段上允许。

Properties are actually methods, they are not serialized by the binary serialization process. 属性实际上是方法,它们不会通过二进制序列化过程进行序列化。 It's the fields that are serialized. 是被序列化的字段。 So it only makes sense to specify NonSerialized on a field. 因此,仅在字段上指定NonSerialized才有意义。

I think this is a case of fine-grained control requiring more effort on your part. 我认为这是一种精细控制的情况,需要您付出更多的努力。 In other words, an automatic property will by default have a serializable backing field. 换句话说,默认情况下,自动属性将具有可序列化的后备字段。 If you want anything other than the default, then you can't use an automatic property. 如果要使用默认值以外的任何其他内容,则不能使用自动属性。

I had thought that using [field:NonSerialized] against the property might work, but it does not. 我以为对属性使用[field:NonSerialized]可能有效,但无效。 The C# spec does not explicitly call out the serializability of the backing field, but it does include this (10.7.3): 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; } }
}

Thus, the backing field is serializable (the default). 因此,支持字段是可序列化的(默认值)。

You may want to look at IgnoreDataMemberAttribute if you're using WCF. 如果使用的是WCF,则可能需要查看IgnoreDataMemberAttribute This works on auto-properties. 这适用于自动属性。

Works even if you don't mark all the other members as DataMember (which I always find to be a pain) and the class with DataContract 即使您没有将所有其他成员都标记为DataMember (我总是觉得很痛苦)并且使用DataContract将该类标记为有效

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

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