简体   繁体   English

XmlSerializer没有序列化自定义类型

[英]XmlSerializer not serializing custom type

I am trying to serialize by following code 我试图通过以下代码序列化

var data = argsPerCall.ToArray();
var knownTypes = new[] { typeof(int), typeof(int),  
                         typeof(string), typeof(McPosition)};

var serializer = new XmlSerializer(data.GetType(), knownTypes);
// Writing the file requires a TextWriter.
var myStreamWriter = new StreamWriter(filename);
serializer.Serialize(myStreamWriter, data);
myStreamWriter.Close();

I am having an issue with McPosition type. 我遇到了McPosition类型的问题。

For following input 用于以下输入

5 , 1, "R251" , {1,2,3}

I am getting following serialization 我正在进行序列化

<ArrayOfAnyType>
    <anyType xsi:type="xsd:int">5</anyType>
    <anyType xsi:type="xsd:int">1</anyType>
    <anyType xsi:type="xsd:string">R251</anyType>
    <anyType xsi:type="McPosition" />
  </ArrayOfAnyType>

Any idea why it wasnt serialized correctly ? 知道为什么它没有正确序列化?

EDIT: 编辑:

public struct McPosition : IComparable<McPosition> {
    private readonly int _station;
    private readonly int _slot;
    private readonly int _subslot;


    public static McPosition Empty = new McPosition(-1, -1, -1);


    public McPosition(int station, int slot, int subslot) {
      _station = station;
      _slot    = slot;
      _subslot = subslot;
    }

etc.... 等等....

Thanks . 谢谢 。

To be serializeable via XmlSerializer , each property on a type must have a public getter and setter (and not be marked [XmlIgnore] nor have a ShouldSerialize*() that returns false, etc). 要通过XmlSerializer进行序列化,类型上的每个属性都必须具有公共getter和setter(并且不标记为[XmlIgnore]也不具有返回false的ShouldSerialize*()等)。 Public fields are also serialized (as long as they aren't readonly ), but exposing fields is even less desirable. 公共字段也是序列化的(只要它们不是readonly ),但是暴露字段更不可取。 XmlSerializer never looks at private members. XmlSerializer从不查看私有成员。

I'm guessing (edit: now confirmed by the updated question) that McPosition is an immutable vector, without public setters. 猜测 (编辑:现在由更新的问题确认) McPosition是一个不可变的向量,没有公共setter。 That won't work. 那不行。 Options: 选项:

  • implement IXmlSerializable (not overly nice, to be honest) 实现IXmlSerializable (不是太好了,说实话)
  • add public setters to McPosition 将公共设置者添加到McPosition
  • use a separate DTO that is fully mutable 使用完全可变的单独DTO

You must add public getter and setter for XML serializable fields. 您必须为XML可序列化字段添加公共getter和setter。 Here : Station, Slot and Subslot. 这里:车站,老虎机和子地块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM