这只是声明性序列化的固有限制,其中类型信息未嵌入到输出中。
关于尝试将<Flibble Foo="10" /> 转换回
public class Flibble { public object Foo { get; set; } }
序列化器如何知道它应该是一个 int、一个字符串、一个 double(或其他)...
要完成这项工作,您有多种选择,但如果您真的不知道直到运行时,最简单的方法可能是使用XmlAttributeOverrides。
遗憾的是,这只适用于基类,不适用于接口。您可以做的最好的事情就是忽略不足以满足您的需求的属性。
如果你真的必须使用界面,你有三个真正的选择:
隐藏它并在另一个属性中处理它
丑陋,令人不快的样板和大量重复,但该课程的大多数消费者不必处理这个问题:
[XmlIgnore()]
public object Foo { get; set; }
[XmlElement("Foo")]
[EditorVisibile(EditorVisibility.Advanced)]
public string FooSerialized
{
get { /* code here to convert any type in Foo to string */ }
set { /* code to parse out serialized value and make Foo an instance of the proper type*/ }
}
这很可能成为维护的噩梦......
实现 IXmlSerializable
与第一个选项类似,您可以完全控制事物,但
- 优点
- 您没有任何令人讨厌的“假”属性。
- 您可以直接与 xml 结构交互,增加灵活性/版本控制
- 缺点
重复工作的问题与第一个类似。
修改您的属性以使用包装类型
public sealed class XmlAnything<T> : IXmlSerializable
{
public XmlAnything() {}
public XmlAnything(T t) { this.Value = t;}
public T Value {get; set;}
public void WriteXml (XmlWriter writer)
{
if (Value == null)
{
writer.WriteAttributeString("type", "null");
return;
}
Type type = this.Value.GetType();
XmlSerializer serializer = new XmlSerializer(type);
writer.WriteAttributeString("type", type.AssemblyQualifiedName);
serializer.Serialize(writer, this.Value);
}
public void ReadXml(XmlReader reader)
{
if(!reader.HasAttributes)
throw new FormatException("expected a type attribute!");
string type = reader.GetAttribute("type");
reader.Read(); // consume the value
if (type == "null")
return;// leave T at default value
XmlSerializer serializer = new XmlSerializer(Type.GetType(type));
this.Value = (T)serializer.Deserialize(reader);
reader.ReadEndElement();
}
public XmlSchema GetSchema() { return(null); }
}
使用它会涉及到类似(在项目 P 中):
public namespace P
{
public interface IFoo {}
public class RealFoo : IFoo { public int X; }
public class OtherFoo : IFoo { public double X; }
public class Flibble
{
public XmlAnything<IFoo> Foo;
}
public static void Main(string[] args)
{
var x = new Flibble();
x.Foo = new XmlAnything<IFoo>(new RealFoo());
var s = new XmlSerializer(typeof(Flibble));
var sw = new StringWriter();
s.Serialize(sw, x);
Console.WriteLine(sw);
}
}
给你:
<?xml version="1.0" encoding="utf-16"?>
<MainClass
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Foo type="P.RealFoo, P, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<RealFoo>
<X>0</X>
</RealFoo>
</Foo>
</MainClass>
虽然避免了很多样板,但这对于类用户来说显然更麻烦。
一个愉快的媒介可能会将 XmlAnything 想法合并到第一种技术的“支持”属性中。通过这种方式,大部分繁重的工作都为您完成了,但该类的消费者不会受到任何影响,只会产生自省的困惑。