简体   繁体   中英

Method to populate a List<string> with class constant values. C#

I'm in need to create a method which allows me to populate a List<string> with the values of the constants that are defined in the own class.

To give you a quick example of the numerous ( 20 in total) const ants that are defined in the class:

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

As you can see, the name of the constant equals the value of it, if that can help.

So far, looking at examples of different types of solutions that I've found in StackOverflow about similar problems, I've come up with this:

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;
}

My experience as a programmer is quite low, same as my experience with C#; I'm not sure if type.GetType().GetProperties() references the constant names, same happens with the property.Name line.

Does this method do what I'm asking?

In order to get const s you should operate with fields , not properties :

  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();
  } 

If you want to get both const names and values:

  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); 
  } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM