如何编写C#扩展方法批量修改类中所有string类型属性值
C# 实现批量为模型类所有string属性追加指定文本的扩展方法
实现代码
using System.Reflection; public static class ModelExtension { /// <summary> /// 为实例对象所有可写的string类型属性追加指定文本 /// </summary> /// <typeparam name="T">模型类类型</typeparam> /// <param name="instance">目标类实例</param> /// <param name="appendText">要追加的文本内容</param> /// <returns>修改后的原实例对象</returns> public static T AppendTextToAllStringProperties<T>(this T instance, string appendText) where T : class { if (instance == null) return null; // 获取当前类所有公共实例属性 PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in properties) { // 仅处理类型为string、支持写入的属性 if (prop.PropertyType == typeof(string) && prop.CanWrite) { string originalValue = prop.GetValue(instance) as string; string newValue = originalValue + appendText; prop.SetValue(instance, newValue); } } return instance; } }
使用示例
首先定义你的业务模型类:
public class YourBusinessModel { public int IntProp1 { get; set; } public int IntProp2 { get; set; } public string StrProp1 { get; set; } public string StrProp2 { get; set; } // 剩余8个string属性按实际需求定义即可 }
调用扩展方法的代码:
// 实例化模型 var model = new YourBusinessModel { IntProp1 = 123, IntProp2 = 456, StrProp1 = "初始文本", StrProp2 = null }; // 批量追加指定文本 model = model.AppendTextToAllStringProperties("some text");
执行后int属性值完全不变,所有string属性都会完成文本拼接,原值为null的string属性会直接被赋值为some text。
可选优化点
- 如果需要排除部分string属性不参与修改,可以给要排除的属性添加自定义特性,遍历属性时做过滤即可
- 对性能要求高的场景可以提前缓存对应类型的string属性元数据,避免每次调用都重复反射查询
内容的提问来源于stack exchange,提问作者tad
相关产品推荐
相关产品推荐

