我在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."
任何帮助?
答案 0 :(得分:3)
扩展评论:
我认为问题在于您使用XmlSerializer
创建了typeof(object)
。
如果您使用以下任何一项,它应该有效:
XmlSerializer xs = new XmlSerializer(myDynamicType);
XmlSerializer xs = new XmlSerializer(instance.GetType());