c# - Xmlserializer 不序列化基类成员

标签 c# .net 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
{
}

同样从 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/

相关文章:

c# - 我应该直接绑定(bind)到从网络服务返回的对象吗?

c# - LINQ 多对多关系 - 获取分组对象的列表

c++ - 转换阴影检测和移除的开源代码

c# - 单独项目中的部分类

c# - 同一命名空间如何在具有不同项目的单个解决方案中工作

不同服务器上的 Python 3.5 dill pickling/unpickling : "KeyError: ' ClassType'"

C# dll 引用产生 classnotfound 异常

c# - System.Linq.Enumerable.Max 的 Mono 之间的模糊调用

java - 为什么 C++ 中的 void 方法可以返回空值,而在其他语言中却不能?

java - 转换为动态类在方法调用中崩溃