我有以下類如何添加XmlInclude屬性動態
[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);
但沒有用了。它仍然給出同樣的例外。
有沒有人對如何實現它有任何想法?
我試過這個,但它給了我下面這個異常 「可能不會爲XmlTest.AList類型指定XmlRoot和XmlType屬性。 任何想法爲什麼它即將到來以及如何解決它? – 2010-04-22 10:02:49
@Aindind - 那很奇怪; 「原樣」的例子對我來說工作得很好。你使用的是什麼框架版本? – 2010-04-23 05:21:13
@Anindya - 我試過4.0和2.0(涵蓋3.0和3.5)並且無法重現。你能給出一個更完整的描述嗎? – 2010-04-23 05:25:51