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

为什么不允许这样做?

我知道解决方案

  • 实施等音
  • 切换到XMLSerializer/XMlignore
  • 切换到手动插入属性

这个问题是专门的 为什么 非序列化]不允许在适当的地方,但可以在田野上进行。

有帮助吗?

解决方案

属性实际上是方法,它们不是通过二进制序列化过程序列化的。这是序列化的字段。因此,指定才有意义 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; } }
}

因此,衬底字段是可序列化的(默认值)。

你可能想看看 IgnoreDataMemberAttribute 如果您使用的是WCF。这在自动范围内起作用。

即使您不将所有其他成员标记为 DataMember (我总是认为这是痛苦的)和 DataContract

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top