C#序列化/反序列化Listview

C#序列化/反序列化Listview,c#,winforms,listview,serialization,listviewitem,C#,Winforms,Listview,Serialization,Listviewitem,我试图序列化ListView中的数据,然后对其进行反序列化,并用保存的数据填充ListView public List<ListViewItem> SaveListView(ListView LV) { System.Collections.Generic.List<ListViewItem> lSavedLV = new List<ListViewItem>(); for (int i = 0; (i <=

我试图序列化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 LV)
{
System.Collections.Generic.List lSavedLV=新列表();

对于(int i=0;(i这里不想光顾,但ListView是表示逻辑。ListViewItem是表示逻辑。您不应该序列化它们。您应该做的是序列化数据,而不是它的可视化表示

为什么不创建一个包含要可视化的数据的类呢

public class DataIWannaVisualize
{
    // ...
}
通过为其指定适当的属性使其可序列化:

[Serializable]
public class DataIWannaVisualize
并具有这些数据对象的列表

IList<DataIWannaVisualize> dataList = new List<DataIWannaVisualize>();
现在是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"; }
        }
    }

}
使用系统;
使用System.Collections.Generic;
使用System.Windows.Forms;
名称空间数据示例
{
公开课表格1:表格
{
私有字符串_Filename=“myanives.xml”;
公共列表myAnimals=新列表();
公共表格1()
{
初始化组件();
}
公共无效注册表日志(字符串名称)
{
添加(新狗{Name=Name});
}
公共无效注册表地址(字符串名称)
{
添加(新的Cat{Name=Name});
}
私有DataGridView dataGridView1;
私人按钮1;
私人按钮2;
/// 
///必需的设计器变量。
/// 
private System.ComponentModel.IContainer components=null;
/// 
///清理所有正在使用的资源。
/// 
///如果应释放托管资源,则为true;否则为false。
受保护的覆盖无效处置(布尔处置)
{
if(处理和(组件!=null))
{
组件。Dispose();
}
基地。处置(处置);
}
#区域Windows窗体设计器生成的代码
/// 
///设计器支持所需的方法-不修改
///此方法的内容与代码编辑器一起使用。
/// 
私有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();
这个.SuspendLayout();
// 
//dataGridView1
// 
this.dataGridView1.allowUserToAddress=false;
this.dataGridView1.AllowUserToDeleteRows=false;
this.dataGridView1.columnHeadershightSizeMode=System.Windows.Forms.datagridviewColumnHeadershightSizeMode.AutoSize;
this.dataGridView1.Location=新系统.Drawing.Point(12,12);
this.dataGridView1.Name=“dataGridView1”;
this.dataGridView1.Size=新系统.Drawing.Size(260199);
this.dataGridView1.TabIndex=0;
// 
//按钮1
// 
this.button1.Location=新系统图纸点(12229);
this.button1.Name=“button1”;
this.button1.Size=新系统图纸尺寸(85,21);
this.button1.TabIndex=1;
this.button1.Text=“保存到文件”;
this.button1.UseVisualStyleBackColor=true;
this.button1.Click+=新系统.EventHandler(this.button1\u Click);
// 
//按钮2
// 
this.button2.Location=新系统图纸点(151229);
this.button2.Name=“button2”;
this.button2.Size=新系统图纸尺寸(121,21);
this.button2.TabIndex=2;
this.button2.Text=“生成虚拟对象”;
this.button2.UseVisualStyleBackColor=true;
this.button2.Click+=新系统.EventHandler(this.button2\u Click);
// 
//表格1
// 
此.AutoScaleDimensions=新系统.Drawing.SizeF(6F,13F);
this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize=新系统.Drawing.Size(284262);
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\u Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
此选项为.resume布局(false);
}
#端区
私有无效按钮2\u单击(对象发送者,事件参数e)
{
注册狗(“SomeDog”);
注册猫(“SomeCat”);
dataGridView1.DataSource=null;
dataGridView1.DataSource=myAnimals;
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
尝试
{
使用(System.Xml.XmlWriter XmlWriter=System.Xml.XmlWriter.Create(_Filename))
{
System.Xml.Serialization.XmlSerializer serializer=new System.Xml.Serialization.XmlSerializer(typeof(List),new Type[]{typeof(Dog),typeof(Cat)});
serializer.Serialize(xmlWriter,myAnimals);
}
}
捕获{}
}
私有void Form1\u加载(对象发送方、事件参数e)
{
尝试
{
使用(System.Xml.XmlReader=System.Xml.XmlReader.Create
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);
    }
}
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"; }
        }
    }

}