希望这个问题不是太明显,但是我已经迈出了序列化主题的第一步,无法找到以下行为的解释:
我想序列化一个类来测试我是否正确设置了所有内容。为此我采取了the code from this tutorial并改编如下:
private void SerializePresets(string path)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyClass));
using (TextWriter writer = new StreamWriter(path))
{
xmlSerializer.Serialize(writer, this);
}
}
这种方法位于MyClass
内,也可以从那里调用。这给了我以下例外:
System.Xml.dll中发生类型为“System.InvalidOperationException”的异常,但未在用户代码中处理
附加信息:有一个错误反映了'MyClass'类型。
由于MyClass
首先将其他类对象作为属性,我认为我也必须制作那些serializabel,但异常仍然存在。所以,我的猜测是,不可能序列化this
,但是我无法找到这个猜测的确认。
编辑:此属性根据内部异常导致问题:
[XmlArray("VolumePresetList"), XmlArrayItem(typeof(LinearAxisColorPresetsModel), ElementName = "VolumePresetList")]
public ObservableCollection<LinearAxisColorPresetsModel> VolumePresetList { get; set; }
你可以用它。它必须是像Dictionary这样不能序列化的属性之一。请参阅下面的示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication103
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.Serialize(FILENAME);
}
}
public class MyClass
{
public string test { get; set; }
public void Serialize(string filename)
{
SerializePresets(filename);
}
private void SerializePresets(string path)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyClass));
using (TextWriter writer = new StreamWriter(path))
{
xmlSerializer.Serialize(writer, this);
}
}
}
}
借助内部异常(再次感谢提示),我可以找出序列化失败的原因。
类LinearAxisColorPresetsModel
did没有无参数的构造函数,这导致了这个问题。
简单地添加
/// <summary>
/// Default Constructor
/// </summary>
private LinearAxisColorPresetsModel()
{
}
这个班为我解决了这个问题。剩下的就是找出原因,为什么我们必须有一个无参数的构造函数。