如何在C#中读写文本文件的List<>?新手求助创建数据读写类
RealObject类与List<>文件读写指南 Hey there! No need to feel self-conscious about being a beginner—every programmer starts exactly where you are right now. Let's walk through building your RealObject class step by step, and cover how to handle List<> file operations in C#.
1. 先搭建RealObject的核心结构
我们需要一个类来存储任意类型的属性,所以用Dictionary<string, object>来保存键值对是个不错的选择——它能灵活容纳不同类型的数据(字符串、List
using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Threading.Tasks; public class RealObject { // 存储所有属性的字典 private Dictionary<string, object> _properties = new Dictionary<string, object>(); // 对象名称(比如你例子里的"John") public string Name { get; } public RealObject(string name) { Name = name; } // 添加属性的方法 public void AddCharacter(string key, object value) { // 如果键已存在,覆盖旧值;否则新增 if (_properties.ContainsKey(key)) _properties[key] = value; else _properties.Add(key, value); } }
2. 实现异步保存到文件的方法
我们用.NET内置的System.Text.Json来序列化数据——它不需要额外安装包,对新手友好。因为要处理List这类复杂类型,JSON是比传统.ini更合适的格式(你依然可以用.ini作为文件名,只是内容用JSON存储)。
在RealObject类里添加以下方法:
public async Task SaveToFileAsync(string filePath) { // 序列化整个对象的属性(包括Name和_properties) var options = new JsonSerializerOptions { WriteIndented = true, // 格式化输出,方便阅读 IncludeFields = true // 因为_properties是私有字段,需要显式包含 }; string json = JsonSerializer.Serialize(this, options); // 异步写入文件 await File.WriteAllTextAsync(filePath, json); }
3. 实现异步从文件读取的方法
同样用System.Text.Json反序列化,把文件里的JSON数据还原成RealObject实例:
public static async Task<RealObject> ReadFromFileAsync(string filePath) { // 注意:这里用静态方法,因为我们要创建一个新的RealObject实例 string json = await File.ReadAllTextAsync(filePath); var options = new JsonSerializerOptions { IncludeFields = true }; return JsonSerializer.Deserialize<RealObject>(json, options); }
4. 添加获取属性的方法
为了安全地获取指定类型的属性,我们可以写一个泛型方法,这样你就能像student.GetValue<List<double>>("Grade")这样获取值:
public T GetValue<T>(string key) { if (_properties.TryGetValue(key, out var value)) { // 尝试将值转换为目标类型 if (value is T typedValue) return typedValue; else throw new InvalidCastException($"无法将属性{key}转换为类型{typeof(T)}"); } else { throw new KeyNotFoundException($"找不到键为{key}的属性"); } } // 可选:添加一个安全的获取方法,返回默认值而不是抛出异常 public T GetValueOrDefault<T>(string key, T defaultValue = default) { if (_properties.TryGetValue(key, out var value) && value is T typedValue) return typedValue; return defaultValue; }
5. 单独聊聊List<>的文件读写
如果你需要单独读写List(不通过RealObject),可以用同样的JSON序列化思路:
写入List到文件
public async Task SaveListToFileAsync<T>(List<T> list, string filePath) { string json = JsonSerializer.Serialize(list, new JsonSerializerOptions { WriteIndented = true }); await File.WriteAllTextAsync(filePath, json); }
从文件读取List
public async Task<List<T>> ReadListFromFileAsync<T>(string filePath) { string json = await File.ReadAllTextAsync(filePath); return JsonSerializer.Deserialize<List<T>>(json) ?? new List<T>(); }
测试你的代码
现在你可以按照预期的方式使用RealObject了:
// 创建对象并添加属性 RealObject john = new RealObject("John"); john.AddCharacter("Full Name", "Something John"); john.AddCharacter("Grade", new List<double> { 9.9, 8.8, 7.7 }); // 保存到文件 await john.SaveToFileAsync("Test.ini"); // 从文件读取 RealObject student = await RealObject.ReadFromFileAsync("Test.ini"); // 获取属性 string fullName = student.GetValue<string>("Full Name"); List<double> grades = student.GetValue<List<double>>("Grade"); Type valueType = grades.GetType(); // 获取值的类型
小提示
- 如果一定要严格用.ini格式(键=值),处理List会比较麻烦,需要自己写解析逻辑(比如把List转成逗号分隔的字符串,读取时再拆分转换),但JSON更适合处理复杂数据类型,推荐使用。
- 记得在项目里引用
System.Text.Json(.NET Core 3.0+和.NET 5+默认包含,.NET Framework需要安装NuGet包)。
内容的提问来源于stack exchange,提问作者Ngo

