我在尝试使用 XmlSerializer 序列化一个用于日志记录的类时遇到了这个非常奇怪的问题。该代码由 wsdl.exe 工具生成。被序列化为的类声明如下:
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "xxxxx")]
public partial class InheritedRequestA : BaseRequest
{
}
同样从 BaseRequest 继承的其他类的序列化包括所有非继承成员,但不包括来自 BaseRequest 的公共(public)成员。 BaseRequest声明如下。
[System.Xml.Serialization.XmlIncludeAttribute(typeof(InheritedRequestA))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(InheritedRequestB))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "xxxxx")]
public partial class BaseRequest
{
//members here
}
为了将请求和响应一起序列化,我编写了一个非常基本的 Wrapper 类,它只包含一个请求对象和一个响应对象。序列化代码:
XmlSerializer serializer = new XmlSerializer(typeof(Wrapper));
string serializedObject = string.Empty;
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, wrapper);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream))
{
serializedObject = reader.ReadToEnd();
}
}
任何关于为什么从基类继承的公共(public)属性没有被序列化的想法将不胜感激。
编辑:这是包装类。我已将它分割为 ActivatorWrapper 和 VersionRetrieverWrapper。
[Serializable]
[XmlInclude(typeof(Wrapper))]
[XmlInclude(typeof(ActivatorWrapper))]
[XmlInclude(typeof(VersionRetrieverWrapper))]
public class Wrapper
{
}
[Serializable]
public class VersionRetrieverWrapper : Wrapper
{
public InheritedRequestA Request { get; set; }
public InheritedResponseA Response { get; set; }
}
最佳答案
您需要确保为 BaseRequest
的公共(public)成员分配了值(无论是在默认构造函数中、在它们的声明中还是在您的服务代码中)。如果不是,XmlSerializer 将忽略它们,除非它们都可以为 null (int?bool?
)并且具有 XML IsNullable属性设置为 true ([XmlElement(IsNullable = true)]
)。
关于c# - Xmlserializer 不序列化基类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567678/