【问题标题】:'XamlParseException' when saving lists using XmlSerializer使用 XmlSerializer 保存列表时出现“XamlParseException”
【发布时间】:2013-12-10 01:25:55
【问题描述】:

我正在尝试将我的自定义对象的两个列表保存为List<Vechicle> 类型的第一个列表。

XmlSerializer SerializerObjVechicle = new XmlSerializer(typeof(List<Vechicle>));

然后我得到错误

"一个未处理的异常类型 'System.Windows.Markup.XamlParseException' 发生在 PresentationFramework.dll"

这是我的车课

[Serializable]
public class Vechicle
{

    private int _Id;
    private String _Registration;
    public Vechicle(int id,String registration)
    {
        Id = id;
        Registration = registration;
    }
    public override string ToString()
    {
        return Id.ToString() + " " + Registration;
    }

    #region getters/setters
    public int Id{
        get { return _Id; }
        set { _Id = value; }
    }

    public String Registration
    {
        get { return _Registration; }
        set { _Registration = value; }
    }

    #endregion
}

}

【问题讨论】:

标签: c# xmlserializer


【解决方案1】:

bogza.anton的回答是对的,你需要提供一个不带参数的构造函数,我给出一个这样的例子:

[Serializable]
public class Vechicle
{

    private int _Id;
    private String _Registration;
    public Vechicle()
    {
        _Id = 1;
        _Registration = "default name";
    }
    public Vechicle(int id, String registration)
    {
        Id = id;
        Registration = registration;
    }
    public override string ToString()
    {
        return Id.ToString() + " " + Registration;
    }

    #region getters/setters
    public int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }

    public String Registration
    {
        get { return _Registration; }
        set { _Registration = value; }
    }

    #endregion
}

private void button1_Click(object sender, EventArgs e)
    {
        List<Vechicle> vList = new List<Vechicle>()
        {
            new Vechicle(),
            new Vechicle(),
            new Vechicle{Id=2, Registration="hello"},
            new Vechicle{Id = 100, Registration="world"}
        };

        XmlSerializer SerializerObjVechicle = new XmlSerializer(vList.GetType());
        FileStream fs = new FileStream("d:\\test.xml", FileMode.OpenOrCreate);
        SerializerObjVechicle.Serialize(fs, vList);
    }

我的测试结果如下:

【讨论】:

    【解决方案2】:

    需要添加一个不带参数的构造函数。 或者从接口 ISerializable 继承类。

    http://msdn.microsoft.com/en-us/library/vstudio/ms233843(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      相关资源
      最近更新 更多