學生信息:學號、姓名、性別。無數據庫要求,數據持久化到本地文件,啟動時加載。
| 格式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| JSON (Newtonsoft.Json / System.Text.Json) | 結構化、可讀、支持層級、標準庫 | 頻繁寫入需整文件覆蓋 | 配置、小數據量、跨平台 |
| CSV | Excel 可直接打開、極簡單 | 無類型、逗號轉義麻煩 | 導出報表、數據交換 |
| 二進制序列化 (BinaryFormatter / Protobuf) | 體積小、速度快 | 不可讀、版本兼容難 | 高性能、內部存儲 |
| XML | 自描述、Schema 驗證 | 冗長、解析慢 | 舊系統兼容 |
推薦:JSON,現代 .NET 核心庫 System.Text.Json 無需第三方依賴。
public class Student {
public string StudentId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public override string ToString() => $"{StudentId}\t{Name}\t{Gender}";
}
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
public class StudentRepository {
private readonly string _filePath = "students.json";
private List<Student> _cache;
public StudentRepository() {
Load();
}
public List<Student> GetAll() => new List<Student>(_cache);
public void Add(Student s) {
if (_cache.Any(x => x.StudentId == s.StudentId))
throw new ArgumentException("學號已存在");
_cache.Add(s);
Save();
}
public bool Remove(string id) {
var s = _cache.FirstOrDefault(x => x.StudentId == id);
if (s == null) return false;
_cache.Remove(s);
Save();
return true;
}
public bool Update(Student s) {
var idx = _cache.FindIndex(x => x.StudentId == s.StudentId);
if (idx < 0) return false;
_cache[idx] = s;
Save();
return true;
}
private void Load() {
if (!File.Exists(_filePath)) {
_cache = new List<Student>();
return;
}
string json = File.ReadAllText(_filePath);
_cache = JsonSerializer.Deserialize<List<Student>>(json) ?? new List<Student>();
}
private void Save() {
var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(_cache, options);
File.WriteAllText(_filePath, json);
}
}
public partial class MainForm : Form {
private readonly StudentRepository _repo = new StudentRepository();
private BindingSource _binding = new BindingSource();
public MainForm() {
InitializeComponent();
_binding.DataSource = _repo.GetAll();
dataGridView1.DataSource = _binding;
}
private void btnAdd_Click(object sender, EventArgs e) {
var s = new Student { StudentId = txtId.Text, Name = txtName.Text, Gender = cbGender.Text };
try { _repo.Add(s); RefreshGrid(); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
private void btnDelete_Click(object sender, EventArgs e) {
if (dataGridView1.CurrentRow?.DataBoundItem is Student s) {
_repo.Remove(s.StudentId);
RefreshGrid();
}
}
private void RefreshGrid() {
_binding.DataSource = _repo.GetAll();
dataGridView1.Refresh();
}
}
Timer 批量持久化。FileShare.None 或遷移至 SQLite(輕量級嵌入式數據庫,單文件,無需安裝)。await File.WriteAllTextAsync(...) 防止 UI 凍結。無數據庫小系統,JSON + Repository 模式 + BindingSource 是最清晰、可維護的方案。代碼分層清晰,後續擴展字段、加密、同步極其容易。