【发布时间】:2010-12-23 14:08:15
【问题描述】:
是否可以序列化通过反射创建的对象?尝试执行通过反射创建的对象的序列化时,出现“无法将类型为 'testNameSpace.ScreenClass' 的对象转换为类型 'testNameSpace.ScreenClass'”的错误。该错误没有意义,因为类型相同,因此强制转换应该成功。没有反射创建的对象的实例可以序列化OK。
编辑: 这是在我的原始帖子中没有正确呈现的代码
//Get the Assembly from file
Assembly webAssembly = Assembly.LoadFile(@"C:\TestAssembly.exe");
//Get the type from assembly
Type screenType = webAssembly.GetType("testNameSpace.ScreenClass");
//get the Constructor for the type (constructor does not take in parameters)
ConstructorInfo ctor = screenType.GetConstructor(new Type[0]);
//create an instance of the type
object screen = ctor.Invoke(new object[] { });
//get the "id" property of type
PropertyInfo screenId = screenType.GetProperty("id");
//populate the "id" property of the instance
screenId.SetValue(screen, "1", null);
Console.WriteLine("value of id property: "
+ (string)screenId.GetValue(screen,null));
//Attempt to serialize the instance of the object created through reflection
try
{
FileStream fs = new FileStream("serialized.xml", FileMode.Create);
XmlSerializer serializer =
new XmlSerializer(typeof(testNameSpace.ScreenClass));
serializer.Serialize(fs, screen); //error occurs here
fs.Close();
}
catch (Exception ex)
{
Console.WriteLine("Message: {0}\nInnerException: {1}\nStack Trace:\n{2}",
ex.Message, ex.InnerException.Message, ex.StackTrace);
}
//Now create instance of object without using reflection and serialize
testNameSpace.ScreenClass screen2 = new testNameSpace.ScreenClass();
screen2.id = "2";
FileStream fs = new FileStream("serialized2.xml", FileMode.Create);
XmlSerializer serializer
= new XmlSerializer(typeof(testNameSpace.ScreenClass));
serializer.Serialize(fs, screen2);
fs.Close();
Console.WriteLine
("\nContents of serialized2.xml:\n" + File.ReadAllText("serialized2.xml"));
从控制台运行时的输出
Message: There was an error generating the XML document.
InnerException: Unable to cast object of type 'testNameSpace.ScreenClass' to type 'testNameSpace.ScreenClass'.
Stack Trace:
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o)
at Program.GetOneProperty() in C:\Code\Serialize.cs:line 96
Contents of serialized2.xml:
<?xml version="1.0"?>
<applicationScreensScreen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="2" />
【问题讨论】:
标签: .net xml reflection serialization