WPF序列化与反序列化

序列化与反序列化

经过比较多种序列化方式,最终决定使用xml序列化,使用xml序列化可以不对类添加属性标签。
定义序列化与反序列化

private void SerializeObject(object obj, string filename)
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
    System.IO.TextWriter writer = new System.IO.StreamWriter(filename);
    serializer.Serialize(writer, obj);
    writer.Close();
}

private object DeSerializeObject(object obj, string filename)
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
    System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
    object obj1 = serializer.Deserialize(fs);
    fs.Close();
    return obj1;
}

使用序列化与反序列化

/// <summary>
/// 保存配置文件
/// </summary>
public void SaveFile()
{
    this.SerializeObject(classCANChanel, "D:\\test.xml");
}
/// <summary>
/// 加载配置文件
/// </summary>
public void LoadFile()
{
    classCANChanel = (ClassCANChanel)this.DeSerializeObject(classCANChanel, "D:\\test.xml");
}
posted @ 2020-10-19 15:25  ycccq  阅读(1041)  评论(0编辑  收藏  举报