我有以下课程
[XmlRoot]
public class AList
{
public List<B> ListOfBs {get; set;}
}
public class B
{
public string BaseProperty {get; set;}
}
public class C : B
{
public string SomeProperty {get; set;}
}
public class Main
{
public static void Main(string[] args)
{
var aList = new AList();
aList.ListOfBs = new List<B>();
var c = new C { BaseProperty = "Base", SomeProperty = "Some" };
aList.ListOfBs.Add(c);
var type = typeof (AList);
var serializer = new XmlSerializer(type);
TextWriter w = new StringWriter();
serializer.Serialize(w, aList);
}
}
现在,当我尝试运行代码时,我在最后一行得到了 InvalidOperationException
类型 XmlTest.C 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。
我知道用 [XmlRoot] 添加一个 [XmlInclude(typeof(C))] 属性可以解决问题。但我想动态地实现它。因为在我的项目中,C 类在加载之前是未知的。C 类正在作为插件加载,因此我无法在其中添加 XmlInclude 属性。
我也试过
TypeDescriptor.AddAttributes(typeof(AList), new[] { new XmlIncludeAttribute(c.GetType()) });
前
var type = typeof (AList);
但没有用。它仍然给出同样的例外。
有谁知道如何实现它?