序列化运行时创建的类型

时间:2013-04-05 11:05:56

标签: c# .net serialization reflection.emit

我在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

来对我的对象进行seralize

尝试了这个:

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."

任何帮助?

1 个答案:

答案 0 :(得分:3)

扩展评论:

我认为问题在于您使用XmlSerializer创建了typeof(object)

如果您使用以下任何一项,它应该有效:

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