【问题标题】:User settings XML serialization of an Object对象的用户设置 XML 序列化
【发布时间】:2009-07-17 13:43:17
【问题描述】:

我正在尝试将自定义对象保存为 VB.net 应用程序中的用户设置。该对象由一个 List(Of Pair(Of String, Object)) 组成。 Pair 是一个自定义类,它有两个读/写属性(一个字符串和一个对象)。

如果我将 int、string、datetime 等简单类型作为我对的第二个值,则保存设置不会有任何问题。但是如果我尝试放一些更复杂的东西,比如一个列表,在序列化过程中似乎有问题,我的设置没有保存。

我对中的字符串值是这样序列化的:

<value1>Priority_1</value1>

对象值使用特殊属性进行序列化:

<value2 xsi:type="xsd:int">2</value2>

似乎 Object 类型的值的序列化方式不同,以“记住”对象的真实类型。为什么它不能对 List(Of T) 等更复杂的类型做同样的事情?

您能想到任何简单的解决方法吗?也欢迎任何可能对我有帮助的关于 XML 序列化的提示:-)

【问题讨论】:

    标签: .net vb.net serialization xml-serialization settings


    【解决方案1】:

    它可以对存储在对象中的 int 执行此操作,因为它知道如何序列化 int。它不知道如何序列化你的复杂类型。

    除非您使用[XmlInclude] attribute 告诉它哪些类型可能出现在该对象中。示例:

       [WebMethod()]
       [XmlInclude(typeof(Car)), XmlInclude(typeof(Bike))]
       public Vehicle Vehicle(string licenseNumber) {
          if (licenseNumber == "0") {
             Vehicle v = new Car();
             v.licenseNumber = licenseNumber;
             return v;
          }
          else if (licenseNumber == "1") {
              Vehicle v = new Bike();
              v.licenseNumber = licenseNumber;
              return v;
          }
          else {
             return null;
          }
       }
    

    在哪里

    [XmlRoot("NewVehicle")] 
    public abstract class Vehicle {
        public string licenseNumber;
        public DateTime make;
    }
    
    public class Car : Vehicle {
    }
    
    public class Bike : Vehicle {
    }
    

    【讨论】:

    • 我在我的序列化类上添加了 XmlInclude 属性,它现在可以工作了。非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多