如何在C#静态类中实现获取所有公共成员变量值的方法
实现静态类公共成员值的收集方法
要实现GetItemsValuesList()方法,你可以通过反射遍历静态类的公共静态属性,提取它们的字符串值。因为你的ItemOne、ItemTwo等都是公共静态的string类型属性,反射可以精准获取这些成员并读取值。
完整实现代码如下:
internal static class Items { public static string ItemOne => "test"; public static string ItemTwo => "test two"; public static string ItemThree => "test three"; public static List<string> GetItemsValuesList() { // 获取当前静态类的Type对象 var type = typeof(Items); // 筛选出所有公共、静态、且类型为string的属性 var stringProperties = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Where(prop => prop.PropertyType == typeof(string)); // 遍历属性并获取它们的值,存入列表 var valuesList = new List<string>(); foreach (var prop in stringProperties) { var value = prop.GetValue(null) as string; if (value != null) { valuesList.Add(value); } } return valuesList; } }
关键步骤说明:
typeof(Items):获取静态类的类型信息,这是反射操作的基础。GetProperties(BindingFlags.Public | BindingFlags.Static):指定只获取公共的静态成员,避免拿到实例成员或非公共成员。Where(prop => prop.PropertyType == typeof(string)):过滤出仅string类型的属性,确保只收集目标成员的值。prop.GetValue(null):因为是静态属性,不需要实例对象,传入null即可获取属性值。
调用这个方法后,会返回包含"test"、"test two"、"test three"的字符串列表。
内容的提问来源于stack exchange,提问作者skm
相关产品推荐
相关产品推荐

