.NET中的序列化错误?

Pet*_*sen 4 .net c# serialization soap-serialization

我正在阅读序列化,到目前为止一直在搞乱BinaryFormatter和SoapFormatter.到目前为止,非常好 - 而且所有内容都完美地序列化和反序列化.

但是,当我尝试下面的代码时,我希望我的数据文件不包含Name的信息 - 它确实如此.当我在字段上指定SoapIgnore时,为什么会包含它?

我也试过SoapAttribute("SomeAttribute")Age-field,这也没有任何区别.框架版本设置为2.0,但在3.5和4.0中也是如此.

using System;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System.Xml.Serialization;

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();
        p.Age = 42;
        p.Name = "Mr Smith";

        SoapFormatter formatter = new SoapFormatter();
        FileStream fs = new FileStream(@"c:\test\data.txt", FileMode.Create);

        formatter.Serialize(fs, p);
    }
}

[Serializable]
class Person
{
    public int Age;
    [SoapIgnore]
    public string Name;
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 9

[NonSerialized]而不是[SoapIgnore]

此外,这是一个较旧(和老化)的API.没有直接错误,但一定要阅读XmlSerializationProtoBuf.

并且小心不要混淆API.序列化是SOAP通信的一部分,但不一样.SoapAttribute不参与裸序列化.