簡體   English   中英

序列化運行時創建的類型

[英]Serialize run-time created type

我已經根據MSDN doc使用System.Reflection.Emit創建了一個類型

我使用以下代碼創建類型和實例:

//following the tutorial I created a method which returns a dynamic type
Type myDynamicType = CreateNewObject("MyDynamicType", fields);
var instance = Activator.CreateInstance(myDynamicType);

現在我想用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."

有什么幫助嗎?

擴展評論:

我認為問題在於您正在使用typeof(object)創建XmlSerializer

如果使用以下兩種方法之一,則應該可以使用:

XmlSerializer xs = new XmlSerializer(myDynamicType);
XmlSerializer xs = new XmlSerializer(instance.GetType());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM