c#序列化/反序列化Listview
本文关键字:Listview 反序列化 序列化 | 更新日期: 2023-09-27 18:12:36
我正试图从ListView序列化数据,然后反序列化它,也因此用保存的数据填充ListView。
public List<ListViewItem> SaveListView(ListView LV)
{
System.Collections.Generic.List<ListViewItem> lSavedLV = new List<ListViewItem>();
for (int i = 0; (i <= animalList.Count - 1); i++)
{
lSavedLV.Add(LV.Items[i]);
}
return lSavedLV;
}
对于储蓄部分,这是一个合理的解决方案吗?如果我打算用这种序列化的数据填充ListView,这是要走的路吗?这是一个匹配的加载方法吗?
public ListView LoadListView(List<ListViewItem> L)
{
ListView lv = new ListView();
for (int i = 0; (i <= (L.Count - 1)); i++)
{
ListViewItem lvi = new ListViewItem();
lvi = ((ListViewItem)(L[i]));
lv.Items.Add(lvi);
}
return lv;
}
我的思想真的徘徊,我一直在尝试一些不同的事情,但似乎有一些错误的加载/填充ListView。这是细节视图。想法,建议?
我不想在这里居高临下,但ListView是一种表示逻辑。ListViewItem是表示逻辑。你不应该序列化它们。你应该做的是序列化你的数据,而不是它的可视化表示。
为什么不创建一个包含要可视化的数据的类呢?
public class DataIWannaVisualize
{
// ...
}
通过给它适当的属性使它可序列化:
[Serializable]
public class DataIWannaVisualize
并有这些数据对象的列表。
IList<DataIWannaVisualize> dataList = new List<DataIWannaVisualize>();
此列表包含您将要使其可见的数据,您将对其进行更改,等等。当然,它也可以很容易地序列化或反序列化。
using (Stream stream = File.Open("data.bin", FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, dataList);
}
现在,你的ListView。通过在表单的Load事件上使用处理程序来填充它。
private void Form1_Load(object sender, EventArgs e)
{
foreach (DataIWannaVisualize dataObject in dataList)
{
ListViewItem item = new ListViewItem();
// TODO: Fill the item with the desired data.
listView1.Items.Add(item);
}
}
最重要的是,您不必担心序列化UI逻辑类。
Callash已经提供了一个足够的答案,但是如果你想看一个完整的例子…
它不是使用ListView,而是DataGridView…但它会告诉你如何保存数据以及如何加载数据
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DataExample
{
public class Form1 : Form
{
private string _Filename = "MyAnimals.xml";
public List<Animal> myAnimals = new List<Animal>();
public Form1()
{
InitializeComponent();
}
public void RegisterDog(String name)
{
myAnimals.Add(new Dog { Name = name });
}
public void RegisterCat(String name)
{
myAnimals.Add(new Cat { Name = name });
}
private DataGridView dataGridView1;
private Button button1;
private Button button2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(12, 12);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(260, 199);
this.dataGridView1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 229);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(85, 21);
this.button1.TabIndex = 1;
this.button1.Text = "persist to file";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(151, 229);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(121, 21);
this.button2.TabIndex = 2;
this.button2.Text = "make dummy objects";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void button2_Click(object sender, EventArgs e)
{
RegisterDog("SomeDog");
RegisterCat("SomeCat");
dataGridView1.DataSource = null;
dataGridView1.DataSource = myAnimals;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(_Filename))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Animal>), new Type[] { typeof(Dog), typeof(Cat) });
serializer.Serialize(xmlWriter, myAnimals);
}
}
catch { }
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(_Filename))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Animal>), new Type[] { typeof(Dog), typeof(Cat) });
myAnimals = (List<Animal>)serializer.Deserialize(xmlReader);
dataGridView1.DataSource = myAnimals;
}
}
catch { }
}
}
[Serializable]
public abstract class Animal
{
public String Name { get; set; }
public abstract String Species { get; }
}
[Serializable]
public class Dog : Animal
{
public override string Species
{
get { return "Dog"; }
}
}
[Serializable]
public class Cat : Animal
{
public override string Species
{
get { return "Cat"; }
}
}
}
如果它真的必须是一个ListView,你可以使用一个循环,就像Callash在他的Form1_Load(…)中创建一个新的ListViewItems从你的数据一旦它被反序列化…