0

我在序列化对象实例时遇到了一点问题,让一些伪代码自己说话:

List<A> ListOfA = new List<A>();

[Serializable]
public class A
{
public Object Instance;
...
}

[Serializable]
public class B
{
    public String SomeAttribute = "example"; 
}

// This will be called:

void Serialize()
{
    var a = new A();
    a.Instance = new B();
    ListOfA.Add(a);

 // a.Instance = new String("test"); works but List<String>, B, ... throws Invalid Operation Exception when serializing:

    using (TextWriter textWriter = new StreamWriter(filePath, false))
    {
        var xmlSerializer = new XmlSerializer(ListOfA.GetType());
        xmlSerializer.Serialize(textWriter, ListOfA );
    }
}

有人对此有解决方案吗?

我尝试使用XmlInclude没有任何结果。

甚至可以在不知道其类型的情况下序列化 Object 吗?

4

2 回答 2

1

尝试:

[XmlInclude(typeof(B))]
public class A {
  public Object Instance;
}

顺便提一句。[Serializable] 对 xml 序列化没用。

于 2013-07-25T08:16:52.730 回答
0

感谢您的快速响应,但我确实通过向 XmlSerializer 提供第二个参数找到了解决问题的方法:

var xmlSerializer = new XmlSerializer(ListOfA.GetType(), new Type[] { typeof(B) });

这样我就不必将 [XmlInclude(typeof(B))] 添加到 A 类...

于 2013-07-25T08:51:22.637 回答