如何使用反射XML序列化类Type?

时间:2015-02-13 07:02:06

标签: c# .net xml serialization

我在通过反射获得课程后尝试XML序列化一个类。任何人都可以建议我确切的方法。以下是我的代码。

Assembly myassembly = Assembly.LoadFile(myassemblypath);
List<Type> types = myassembly .GetTypes().Where(x => x.BaseType == typeof(myType));
foreach (Type item in types)
{
 dynamic instance = Activator.CreateInstance(item);
 using (var writer = new StringWriter())
{
 new XmlSerializer(item.GetType()).Serialize(writer, instance);
string xmlEncodedList = writer.GetStringBuilder().ToString();
Console.WriteLine(xmlEncodedList);
 }
}

此代码无效,它给了我例外。

1 个答案:

答案 0 :(得分:0)

因为您正在获取system.RuntimeType异常,用于获取您需要从RuntimeType中解包实际类型的实际类型,这将解决您的问题。

以下是解开实际类型的代码

 var runTimeObj = Activator.
               CreateInstance(assemblyName, assemblyName + "." + className);
 //T is generic type as i m using genric
 //but point of interest here is unwrap method to get actual type
 var dataProvider = (T)runTimeObj.Unwrap();

又一个例子

  ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
  Object p = handle.Unwrap();
  Type t = p.GetType();

您使用dynamic的代码使用时的另一个问题请勿使用ObjectHandle ...如示例中所示

用于解包检查:https://msdn.microsoft.com/en-us/library/d133hta4%28v=vs.110%29.aspx