C#中如何为所有类实现ToString?含集合字段类的处理方案
问题1:通过扩展方法为所有类型实现自定义ToString
要给所有类型统一添加自定义ToString逻辑,用泛型扩展方法就能实现,核心是借助反射遍历类型的属性:
- 先创建一个静态类,扩展方法必须放在静态类中
- 定义泛型扩展方法,给泛型参数
T加上this关键字,让所有类型都能调用这个方法 - 用反射获取当前实例的所有公共属性,遍历属性并拼接名称和值
基础实现代码:
public static class ObjectExtensions { public static string ToStringProperty<T>(this T t) { if (t == null) return "null"; var result = new StringBuilder(); foreach (PropertyInfo prop in t.GetType().GetProperties()) { var value = prop.GetValue(t, null); result.AppendLine($"{prop.Name}: {value}"); } return result.ToString().Trim(); } }
调用时直接在任意对象上使用:yourObject.ToStringProperty()
问题2:处理包含集合类型的ToString扩展
如果对象里有List、数组这类集合字段,基础实现只会输出集合的类型名,需要递归处理集合中的每个元素,修正后的扩展方法逻辑如下:
- 判断属性值是否是
IEnumerable且不是string(string本身也是IEnumerable) - 如果是集合,遍历集合中的每个元素,递归调用ToStringProperty
- 普通属性直接拼接名称和值
完整代码:
using System.Reflection; using System.Text; using System.Collections; public static class ObjectExtensions { public static string ToStringProperty<T>(this T t) { if (t == null) return "null"; var result = new StringBuilder(); var type = t.GetType(); // 处理直接传入的集合实例(比如直接传List的情况) if (t is IEnumerable enumerable && !(t is string)) { result.AppendLine($"[{type.Name}]"); int index = 0; foreach (var item in enumerable) { result.AppendLine($" [{index}]: {item.ToStringProperty()}"); index++; } return result.ToString().Trim(); } // 处理普通对象的属性 foreach (PropertyInfo prop in type.GetProperties()) { var value = prop.GetValue(t, null); if (value is IEnumerable propEnumerable && !(value is string)) { result.AppendLine($"{prop.Name}: [{propEnumerable.GetType().Name}]"); int itemIndex = 0; foreach (var item in propEnumerable) { result.AppendLine($" [{itemIndex}]: {item.ToStringProperty()}"); itemIndex++; } } else { result.AppendLine($"{prop.Name}: {value}"); } } return result.ToString().Trim(); } }
代码说明:
- 用
StringBuilder代替字符串拼接,避免频繁创建字符串对象,提升性能 - 增加null判断,防止空引用异常
- 递归处理集合元素,支持多层嵌套集合(比如
List<List<int>>) - 区分普通对象和直接传入的集合实例,输出格式更清晰
调用示例:
public class Person { public string Name { get; set; } public int Age { get; set; } public List<string> Hobbies { get; set; } } var person = new Person { Name = "Alice", Age = 30, Hobbies = new List<string> { "Reading", "Hiking" } }; Console.WriteLine(person.ToStringProperty());
输出结果:
Name: Alice Age: 30 Hobbies: [List`1] [0]: Reading [1]: Hiking
内容的提问来源于stack exchange,提问作者רחלי
相关产品推荐
相关产品推荐

