0
我創建了一個類型與System.Reflection.Emit
以下MSDN doc序列化運行時類型
創建我的類型和與此代碼實例:
//following the tutorial I created a method which returns a dynamic type
Type myDynamicType = CreateNewObject("MyDynamicType", fields);
var instance = Activator.CreateInstance(myDynamicType);
現在我想seralize我的對象與XmlSerializer
嘗試這樣做:
FileStream fs = new FileStream(@"C:\Test\SerializedDynamic.XML", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(object));
xs.Serialize(fs, instance);
但它拋出異常:
"The type MyDynamicType was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
任何幫助嗎?
你嘗試過鑄造?或者這http://msdn.microsoft.com/en-gb/library/e5aakyae.aspx – Sayse 2013-04-05 11:12:10
什麼如果你這樣做了:'XmlSerializer xs = new XmlSerializer(myDynamicType);'? – 2013-04-05 11:17:31
你可以做它說你要做的事嗎?有沒有可能爲您的動態類型添加屬性?主要是'[XmlInclude]'應該告訴它是什麼數據類型。然而,我認爲@JonEgerton發現的確實是什麼問題 - 你必須爲序列化程序提供一個類型(如果將實例作爲參數傳遞給執行序列化的方法,也可以嘗試'new XmlSerializer(instance.GetType())') – Sinatr 2013-04-05 11:28:05