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

为什么不允许这样做?

我知道解决方法,例如

  • 实现 ISerializable
  • 切换到 XmlSerializer/XmlIgnore
  • 切换到手动实现的属性

问题具体是为什么在属性上不允许 [NonSerialized],而在字段上却允许。

4

3 回答 3

12

属性实际上是方法,它们不被二进制序列化过程序列化。它是被序列化的字段。所以只有NonSerialized在字段上指定才有意义。

于 2010-09-21T13:50:25.200 回答
3

我认为这是一个需要您付出更多努力的细粒度控制案例。换句话说,默认情况下,自动属性将具有可序列化的支持字段。如果您想要除默认值以外的任何内容,则不能使用自动属性。

我曾认为[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; } }
}

因此,支持字段是可序列化的(默认)。

于 2010-09-21T13:48:00.413 回答
0

您可能想看看IgnoreDataMemberAttribute您是否使用 WCF。这适用于自动属性。

即使您没有将所有其他成员标记为DataMember(我总是觉得很痛苦)并且课程与DataContract

于 2013-01-04T00:24:07.553 回答