将对象列表保存到XML文件并使用C#加载该列表的最佳方法是什么?

将对象列表保存到XML文件并使用C#加载该列表的最佳方法是什么?,c#,.net,C#,.net,我的应用程序中有一个“手势”类列表: List<Gesture> gestures = new List<Gesture>(); List手势=新建列表(); 这些手势类非常简单: public class Gesture { public String Name { get; set; } public List<Point> Points { get; set; } public List<Point> Transf

我的应用程序中有一个“手势”类列表:

List<Gesture> gestures = new List<Gesture>();
List手势=新建列表();
这些手势类非常简单:

public class Gesture
{
    public String Name { get; set; }
    public List<Point> Points { get; set; }
    public List<Point> TransformedPoints { get; set; }    

    public Gesture(List<Point> Points, String Name)
    {
        this.Points = new List<Point>(Points);
        this.Name = Name;
    }
}
公共类手势
{
公共字符串名称{get;set;}
公共列表点{get;set;}
公共列表转换点{get;set;}
公共手势(列表点、字符串名称)
{
this.Points=新列表(点);
this.Name=Name;
}
}
我想让用户既能将“手势”的当前状态保存到文件中,也能加载包含手势数据的文件

在C#中,标准的方法是什么


我应该使用序列化吗?我应该自己编写一个类来处理写/读这个XML文件吗?还有其他方法吗?

看看.net中的XmlSerializer类型和XmlSerialization

这里。。找到了一个符合您需要的示例

查看DataContactSerializer(在.NET 3.0中引入)。根据您正在执行的操作,它可能是一个更好的选择。

使用通用序列化程序


是的,这是一个非常标准的序列化场景。唯一需要注意的是,我建议使用基于“契约”的东西,例如
xmlserializer
(或者如果您想要二进制文件而不是xml,则使用protobuf-net)。对于
XmlSerializer
,需要添加无参数构造函数,您可能需要添加一些xml装饰以控制格式:

[XmlRoot("gesture")]
public class Gesture
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("point")]
    public List<Point> Points { get; set; }
    [XmlElement("transformedPoint")]
    public List<Point> TransformedPoints { get; set; }    
    public Gesture()
    {
        this.Points = new List<Point>();
    }
    public Gesture(List<Point> Points, String Name)
    {
        this.Points = new List<Point>(Points);
        this.Name = Name;
    }
}
[XmlRoot(“手势”)]
公众阶级姿态
{
[XmlAttribute(“名称”)]
公共字符串名称{get;set;}
[XmlElement(“点”)]
公共列表点{get;set;}
[XmlElement(“transformedPoint”)]
公共列表转换点{get;set;}
公共姿态
{
this.Points=新列表();
}
公共手势(列表点、字符串名称)
{
this.Points=新列表(点);
this.Name=Name;
}
}
然后您可以使用以下命令进行序列化:

XmlSerializer ser = new XmlSerializer(gestures.GetType());
using(var file = File.Create("gestures.xml")) {
    ser.Serialize(file, gestures);
}
...
using(var file = File.OpenRead("gestures.xml")) {
    gestures = (List<Gesture>) ser.Deserialize(file);
}
XmlSerializer ser=新的XmlSerializer(signities.GetType());
使用(var file=file.Create(“signatures.xml”)){
序列化(文件、手势);
}
...
使用(var file=file.OpenRead(“signatures.xml”)){
手势=(列表)序列反序列化(文件);
}

需要注意的一点是,他需要公开一个公共的无参数构造函数才能在此类型上使用XmlSerializer。实际上,我刚刚发现它不必是公共的无参数构造函数。只要是无参数的,私有和内部都可以正常工作。在这种情况下,
Point
是什么?@Marc gravel,System.Windows.Point。