用类常量值填充List<string>的方法。C#

7

我需要创建一个方法,使我能够填充 List<string>,并将其中的值设为类中定义的常量。

这是一个例子,该类中定义了许多常量(一共有 20 个):

private const string NAME1 = "NAME1";
private const string NAME2 = "NAME2";
private const string NAME3 = "NAME3";
...

正如您所见,常量的名称等于其值,如果有帮助的话。

到目前为止,我在StackOverflow上找到了各种类型解决类似问题的示例,我得出了以下结论:

public static List<string> GetConstantNames()
{
   List<string> names = new List<string>();
   Type type = typeof(ClassName);

   foreach (PropertyInfo property in type.GetType().GetProperties())
   {
      names.Add(property.Name);
   }

   return names;
}

我的编程经验很少,对C#的经验也不多。 我不确定 type.GetType().GetProperties() 是否引用常量名称, property.Name 行也是如此。 这个方法是否能够完成我所要求的功能?

1
请不要这样做,如果你想这么做,那肯定是以错误的方式实现了某些东西。你想要达到什么目的? - Marco Salerno
@MarcoSalerno 你好,我的目标是创建一个方法,使我能够创建一个List,其中包含类的常量的值。 在我发布的示例中,调用GetConstantNames()方法时,想要获得一个包含在顶部定义的常量值的List,类似于List<string> names = "NAME1","NAME2","NAME3",... - Jrene
1
是的,但为什么呢?这不是一个好的实践。 - Marco Salerno
1
你是否遇到了x-y问题?你的问题似乎是在询问解决方案,而不是阐述你的根本问题。 - AdrianHHH
1
拥有一组变量名称相等的字符串变量通常最好作为字符串数组(或列表)而存在。另一个可能性是拥有一个枚举类型并使用“.ToString()`”方法将名称转换为字符串。 - AdrianHHH
1个回答

11
为了获得常量,您应该使用字段而不是属性:
  using System.Linq;
  using System.Reflection;

  ...

  public static List<string> GetConstantNames() {
    return typeof(ClassName)
      .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
      .Where(fi => fi.IsLiteral && !fi.IsInitOnly) // constants, not readonly
      .Where(fi => fi.FieldType == typeof(string)) // of type string
      .Select(fi => fi.Name) 
      .ToList();
  } 

如果你想要获取常量名称

  public static Dictionary<string, string> GetConstantNamesAndValues() {
    return typeof(ClassName)
      .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
      .Where(fi => fi.IsLiteral && !fi.IsInitOnly) // constants, not readonly
      .Where(fi => fi.FieldType == typeof(string)) // of type string
      .ToDictionary(fi => fi.Name, fi => fi.GetValue(null) as String); 
  } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接