防止属性被序列化

Dis*_*ame 12 c# wpf

我试过这样的事情:

    [NonSerialized]
    private string _DecodeText;
    public string DecodeText { get { return _DecodeText; } set { _DecodeText = value; } }
Run Code Online (Sandbox Code Playgroud)

但它不起作用."DecodeText"仍在序列化文件中.如何防止属性序列化?

Rus*_*est 24

我怀疑你正在使用XmlSerializer?如果是这样,请改用[XmlIgnore]属性.

这应该应用于属性而不是支持字段作为XmlSerializer序列化公共字段和属性(而BinaryFormatter使用refelction来获取私有字段 - 因此使用BinaryFormatter时使用NonSerialized标记私有字段).


Joh*_*ohn 5

我能够使用以下内容并且没有序列化属性(.NET 4.0):

private string _DecodeText;
[System.Xml.Serialization.XmlIgnore]
public string DecodeText { get { return _DecodeText; } set { _DecodeText = value; } }
Run Code Online (Sandbox Code Playgroud)


Ala*_*anT 2

更新答案

[NonSerialized] 属性位于变量而非属性上,但不能位于属性上。所以这不会有帮助。

防止属性被序列化的一种方法是添加一个方法

public bool ShouldSerializeDecodeText() {
   return false;
}
Run Code Online (Sandbox Code Playgroud)

这(至少对于 XmlSerializer 来说)将阻止属性被序列化。

如果您不想仅仅为了序列化而向类添加大量方法,您可以尝试从它继承并将方法添加到派生类。

嗯,艾伦。