【发布时间】:2014-06-06 11:05:03
【问题描述】:
我搜索了很多并找到了一些解决方案,但它们对我不起作用。我有一些用 WPF 编写的 GUI 创建工具,我希望能够序列化对象的实例。
我已经制作了一个虚拟版本来检查序列化是否正常工作,但我得到了TargetInvocationException。
该项目有两个扩展 CanvasItem 的标签和图像类,一个包含 CanvasItems 集合的布局类,以及一个包含布局集合的项目类。
我写的要序列化的类:
public class XMLWrite
{
public static void WriteXML(LCTProject project)
{
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(LCTProject));
string path = Directory.GetParent(Directory.GetParent(Directory.GetParent(
System.AppDomain.CurrentDomain.BaseDirectory.ToString()).ToString()).ToString()).ToString()
+ project.name + ".xml";
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
writer.Serialize(file, project);
file.Close();
}
public static LCTProject ReadXML(string name)
{
System.Xml.Serialization.XmlSerializer reader =
new System.Xml.Serialization.XmlSerializer(typeof(LCTProject));
string path = Directory.GetParent(Directory.GetParent(Directory.GetParent(
System.AppDomain.CurrentDomain.BaseDirectory.ToString()).ToString()).ToString()).ToString()
+ name + ".xml";
System.IO.StreamReader file = new System.IO.StreamReader(path);
LCTProject project = new LCTProject();
project = (LCTProject)reader.Deserialize(file);
return project;
}
}
以及我如何让它运行:
public MainWindow()
{
InitializeComponent();
LCTLabel label1 = new LCTLabel();
label1.locationX = 6;
label1.locationY = 8;
label1.alignment = CanvasItem.Alignment.Bottom;
label1.text = "hi hi hi";
label1.textSize = 12;
Color clr = new Color();
label1.color = clr;
LCTImage img = new LCTImage();
img.locationX = 1;
img.locationY = 2;
img.alignment = CanvasItem.Alignment.Right;
img.path = @"C:\";
LCTImage img2 = new LCTImage();
img2.locationX = 500;
img2.locationY = 100;
img2.alignment = CanvasItem.Alignment.Up;
img2.path = @"C:\";
LCTLayout layout1 = new LCTLayout();
LCTLayout layout2 = new LCTLayout();
layout1.items.Add(label1);
layout1.items.Add(img);
layout2.items.Add(img);
layout2.items.Add(img2);
LCTProject project = new LCTProject();
project.layouts.Add(layout1);
project.layouts.Add(layout2);
XMLWrite.WriteXML(project);
}
我得到以下异常:
TargetInvocationException 未处理 PresentationFramework.dll 中出现“System.Reflection.TargetInvocationException”类型的未处理异常 附加信息:调用目标引发了异常。
我该如何解决这个问题?
【问题讨论】:
-
您应该始终显示整个异常。出于故障排除目的,请输入
try {XMLWrite.WriteXML(project);}catch(Exception ex){System.Diagnostics.Debug.WriteLine(ex.ToString());throw;}。尝试并发布结果。
标签: c# wpf serialization xml-serialization system.reflection