• Reprint: Serialization


    Having just recently ran into some major serialization issues I’m going to list some of the errors and pitfalls that I ran into.

    Some of the errors encountered

    Error one
    “<ClassName> is inaccessible due to its protection level. Only public types can be processed.”

    It means that the Class you are trying to serialize is not marked as public and hence the serializor can not access it. Depending on the Class scope this may not be a problem e.g. the serialization code and the class are both in the same scope.

    Error Two
    “Cannot serialize member <Property Name> of type <Type> because it is an interface.”

    It means that one of the members in your class is defined as an interface. An interface can never be serialized since the serializor will not know which instance of the interface to use.

    Error Three
    The type <Type> was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

    This error is caused when trying to serialize an inherited class

    E.g. the following example will cause this problem

    1. public class Test  
    2. {  
    3.   private string _Field = "";  
    4.   public string Field  
    5.   {  
    6.     get { return _Field; }  
    7.     set { _Field = value; }  
    8.   }  
    9. }  
    10.   
    11. public class TestInherited : Test  
    12. {  
    13. }  
    14.   
    15. public class Container  
    16. {  
    17.   private Test ivField;  
    18.   public Test Field  
    19.   {  
    20.     get { return _Field; }  
    21.     set { _Field = value; }  
    22.   }  
    23. }  
    24.   
    25. Container _Test = new Container();  
    26. _Test.Field = new TestInherited();  

    The issue is that the Container.Field is defined as Test but instantiated as TestInherited. Their are two solutions for this problem
    1) Add the attribute [XmlInclude(typeof(TestInherited))] to the Test class
    2) new XmlSerializer(typeof(Container), new Type[] { typeof(TestInherited) });

    The second method is preferred. With the first method you have to decorate your base classes to which you may not always have access to, secondly the base class should not be aware of any class that inherits from it.

    Note:特别的,当一个对象中的属性为基类或者object类型时,他的依赖注入的类型(即运行时类型)必须明确使用 XmlInclude属性标明序列化的类型,否则序列化会出错。

    转载自 http://www.johnsoer.com/blog/?p=125

  • 相关阅读:
    Can't connect to X11 window server using 的问题,求解
    自动化运维,让你远离背锅侠
    python netmiko实现cisco网络设备配置备份
    如何备份思科、锐捷、Juniper的配置文件
    网络配置备份。
    使用SecureCRT脚本备份网络设备配置的一点感悟
    網管利器!開源管理系統-LibreNMS
    邮件协议与port
    视频播放技术汇总(列表播放,小窗播放,跨界面播放,播放中网络切换提示)
    android插件式开发资料整理
  • 原文地址:https://www.cnblogs.com/anthonyBlog/p/4346319.html
Copyright © 2020-2023  润新知