[英]How to XML serialize a class Type using reflection?
I'm trying to XML serialize a class after getting the class through reflection. 通过反射获取类后,我试图对一个类进行XML序列化。 Can anyone suggest me the exact method.
谁能建议我确切的方法。 Below is my code.
下面是我的代码。
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);
}
}
This code is not working, it gives me exception. 这段代码不起作用,它给了我异常。
as you are getting system.RuntimeType exception , for getting actual type you need to unwrap actual type from RuntimeType , that will resolve your issue. 当您获取system.RuntimeType异常时,要获取实际类型,您需要从RuntimeType解开实际类型,这将解决您的问题。
following is code to unwrape actual type 以下是解开实际类型的代码
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();
one more example 再举一个例子
ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
Object p = handle.Unwrap();
Type t = p.GetType();
one more problem with you code use of dynamic
dont use it make use of ObjectHandle
...as given in example 代码的另一个问题是使用
dynamic
不要使用它,而是使用ObjectHandle
...如示例中所示
for unwrap check : https://msdn.microsoft.com/en-us/library/d133hta4%28v=vs.110%29.aspx 用于展开检查: https : //msdn.microsoft.com/zh-cn/library/d133hta4%28v=vs.110%29.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.