2013-04-05 40 views
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." 

任何幫助嗎?

+0

你嘗試過鑄造?或者這http://msdn.microsoft.com/en-gb/library/e5aakyae.aspx – Sayse 2013-04-05 11:12:10

+0

什麼如果你這樣做了:'XmlSerializer xs = new XmlSerializer(myDynamicType);'? – 2013-04-05 11:17:31

+0

你可以做它說你要做的事嗎?有沒有可能爲您的動態類型添加屬性?主要是'[XmlInclude]'應該告訴它是什麼數據類型。然而,我認爲@JonEgerton發現的確實是什麼問題 - 你必須爲序列化程序提供一個類型(如果將實例作爲參數傳遞給執行序列化的方法,也可以嘗試'new XmlSerializer(instance.GetType())') – Sinatr 2013-04-05 11:28:05

回答

3

擴大的評論:

我認爲這個問題是,你正在創建的XmlSerializertypeof(object)

如果您使用以下任它應該工作:

XmlSerializer xs = new XmlSerializer(myDynamicType); 
XmlSerializer xs = new XmlSerializer(instance.GetType()); 
相關問題