C#中序列化派生类的问题

时间:2009-12-02 19:51:34

标签: c# .net serialization

我有这样的代码:

[Serializable]
public class A {
    public int X { get; set; }
}
[Serializable]
public class B : A{        
}
[Serializable]
public class C {
    public A A { get; set; }
}
...
    public string Serialize<T>(T obj)
    {
        StringBuilder stringBuilder = new StringBuilder();
        TextWriter stringWriter = new StringWriter(stringBuilder);
        XmlWriter xmlWriter = new XmlTextWriter(stringWriter);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(xmlWriter, obj);
        xmlWriter.Close();
        stringWriter.Close();
        return stringBuilder.ToString();
    }

    private void Run() {
        C c = new C() {A = new B()};
        string str = Serialize(c);
    }      

System.InvalidOperationException执行string str = SerializationManager.Serialize(c);文字"There was an error generating the XML document."

我必须编写代码来c无例外地编写代码吗?

1 个答案:

答案 0 :(得分:7)

你需要告诉它有关继承的信息:

[XmlInclude(typeof(B)]
public class A {
    public int X { get; set; }
}
public class B : A{        
}

请注意[Serializable] 需要XmlSerializer

另外 - 看一下内部异常:

try { ... }
catch (Exception ex) {
    while(ex != null) {
        Console.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
}

要看:

  

“不期望类型B。使用XmlInclude或SoapInclude属性指定静态未知的类型。”