序列化运行时创建的类型
本文关键字:类型 创建 运行时 序列化 | 更新日期: 2023-09-27 18:07:28
我在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
序列化我的对象
try this:
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());