gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:54 25 4
gpt4 key购买 nike

我有这样的代码:

[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);
}

我在执行 string str = SerializationManager.Serialize(c); 时遇到 System.InvalidOperationException 文本 “生成 XML 文档时出错。 "

我必须如何编写我的代码才能无一异常(exception)地序列化 c

最佳答案

你需要告诉它继承:

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

请注意,对于 XmlSerializer,您不需要 [Serializable]

另外 - 查看内部异常:

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

查看:

"The type B was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

关于c# - C#中序列化派生类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1835366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com