我有一个由几种基本类型和接口类型组成的类。我知道您不能简单地反序列化接口类型,因为它不知道使用哪种具体类型。
那么,为什么不能使用Xml属性来定义要使用的具体类型呢?
这是我的代码的简化版本,以显示此问题。错误始终是它无法创建接口类型“ MyType”。如果我将接口类型换成同名的抽象类型(在此我为方便起见已将其注释掉),则它将按预期工作。
我最初从这篇文章中得到的想法表明这应该可行:https://blog.codeinside.eu/2015/10/25/xml-deserialize-to-abstract-class-interface-or-base-class/
class Program
{
static String MultipleInstancesRequired =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<MyComponent>" +
"<Name>Component123</Name>" +
"<SpecialType>" +
"<Description>Some Awesome Component</Description>" +
"<Value>42</Value>" +
"</SpecialType>" +
"</MyComponent>";
static void Main(string[] args)
{
MyComponent comp = PopulateComponent();
}
private static MyComponent PopulateComponent()
{
MyComponent component;
XmlSerializer obj = new XmlSerializer(typeof(MyComponent), new XmlRootAttribute("MyComponent"));
Stream stream = new MemoryStream(Encoding.ASCII.GetBytes(MultipleInstancesRequired));
component = (MyComponent)obj.Deserialize(stream);
return component;
}
}
[Serializable]
public class MyComponent
{
[XmlElement]
public string Name { get; set; }
[XmlElement(typeof(RealType), ElementName = "SpecialType")]
public MyType SpecialType { get; set; }
}
[Serializable]
public class RealType : MyType
{
[XmlElement]
public string Description { get; set; }
[XmlElement]
public int Value { get; set; }
}
public interface MyType
{
string Description { get; set; }
int Value { get; set; }
}
//public abstract class MyType
//{
// [XmlElement]
// public string Description { get; set; }
// [XmlElement]
// public int Value { get; set; }
//}