Xmlserializer没有序列化基类成员

olt*_*man 3 .net c# serialization xml-serialization

在尝试使用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
{
}
Run Code Online (Sandbox Code Playgroud)

同样继承自BaseRequest的其他类的序列化包括所有非继承成员,但不包括BaseRequest中的所有公共成员.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
}
Run Code Online (Sandbox Code Playgroud)

为了将请求和响应一起序列化,我编写了一个非常基本的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();
            }
        }
Run Code Online (Sandbox Code Playgroud)

关于为什么从基类继承的公共属性没有被序列化的任何想法将不胜感激.

编辑:这是包装类.我将它子类化为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; }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ate 5

您需要确保为其BaseRequest分配了值的公共成员(无论是在默认构造函数中,在其声明中,还是在服务的代码中).如果没有,XmlSerializer将忽略它们,除非它们都是nullable(int? bool?) 并且 XML IsNullable属性设置为true([XmlElement(IsNullable = true)]).