このサンプルコードは、クラスSampleのリストをシリアライズ(保存)し、またデシリアライズ(読み出し)する方法を示しています。このページでは保存した時のデータはバイナリで、ファイルを開いてもそのままでは視認できない状態です。ファイルを開いて確認したい場合はXML形式でのシリアライズすることも可能です。
クラスの宣言に対してSerializable属性をつけますが、実は保存したくないフィールドがある場合、それに対してNonSerializable属性をつけると保存されません。
また、プロパティを設定していても、プライベートなフィールドでもそれに対して直接シリアライズ、デシリアライズが行われるので、プロパティの中で計算処理があっても、実行されません。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace SerializationForClass
{
public partial class Form1 : Form
{
private List<sample> _data = new List<sample>();
private int _index;
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Sample local = new Sample();
local.BirthDay = this.dateTimePicker1.Value;
local.Name = this.textBox3.Text;
local.ID = this._data.Count;
this._data.Add(local);
}
private void btnNext_Click(object sender, EventArgs e)
{
_index++;
if (_data.Count <= _index)
{
_index = _data.Count - 1;
}
this.textBox1.Text = _data[_index].ID.ToString();
this.textBox2.Text = _data[_index].Age.ToString();
this.textBox3.Text = _data[_index].Name;
this.dateTimePicker1.Value = _data[_index].BirthDay;
}
private void btnPrev_Click(object sender, EventArgs e)
{
_index--;
if (_index < 0)
{
_index = 0;
}
this.textBox1.Text = _data[_index].ID.ToString();
this.textBox2.Text = _data[_index].Age.ToString();
this.textBox3.Text = _data[_index].Name;
this.dateTimePicker1.Value = _data[_index].BirthDay;
}
private void btnSave_Click(object sender, EventArgs e)
{
BinaryFormatter formatter = new BinaryFormatter();
Stream s = new FileStream("D:\\Data.dat", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(s, _data);
s.Close();
}
private void btnLoad_Click(object sender, EventArgs e)
{
BinaryFormatter formatter = new BinaryFormatter();
Stream s = new FileStream("D:\\Data.dat", FileMode.Open, FileAccess.Read, FileShare.None);
_data = (List<sample>)formatter.Deserialize(s);
s.Close();
}
}
[Serializable]
public class Sample
{
private string _name;
[NonSerialized]
private int _age;
private DateTime _birthday;
private int _id;
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
}
public DateTime BirthDay
{
get { return _birthday; }
set
{
_birthday = value;
TimeSpan temp = DateTime.Today-this._birthday;
this._age = (int)(temp.Days / 365);
}
}
public int ID
{
get { return _id; }
set { _id = value; }
}
}
}
