如何在泛型函数中传递并遍历List<T>以批量重置类静态变量
实现方案
核心代码
using System.Reflection; using System.Collections.Generic; public static class HelperClass { // 保留原有单个类的泛型调用方法,兼容旧代码 public static void ResetStaticObjects<T>() { ResetSingleTypeStaticObjects(typeof(T)); } // 新增批量处理方法,支持传入Type列表 public static void ResetStaticObjects(IEnumerable<Type> types) { foreach (var type in types) { ResetSingleTypeStaticObjects(type); } } // 抽取公共的单类型重置逻辑 private static void ResetSingleTypeStaticObjects(Type type) { if (type == null) return; var staticProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Static); foreach (var property in staticProperties) { // 跳过不可写的静态属性,避免运行时报错 if (!property.CanWrite) continue; // 处理值类型属性,避免赋值null抛出异常 object defaultValue = property.PropertyType.IsValueType ? Activator.CreateInstance(property.PropertyType) : null; // 静态属性赋值不需要实例对象,第一个参数传null即可 property.SetValue(null, defaultValue); } } }
调用示例
// 传入需要重置的类的Type列表即可 HelperClass.ResetStaticObjects(new List<Type> { typeof(DemoClass), typeof(AnotherDemoClass), typeof(ThirdDemoClass) });
优化说明
- 完全兼容原有调用逻辑,旧的单泛型调用方式
HelperClass.ResetStaticObjects<DemoClass>()无需修改即可正常运行 - 新增不可写属性过滤逻辑,避免遇到静态只读属性时抛出运行时异常
- 修复了原方法对值类型静态属性赋值null报错的问题,会自动为值类型属性设置对应默认值(如int设为0、bool设为false等)
- 修正了原方法静态属性赋值时传入type作为实例参数的不规范写法,静态成员赋值时实例参数统一传null即可
内容的提问来源于stack exchange,提问作者Learning
相关产品推荐
相关产品推荐

