How can I get the name of a C# static class property using reflection?

后端 未结 5 1349
孤街浪徒
孤街浪徒 2020-12-11 22:41

I want to make a C# Dictionary in which the key is the string name of a static property in a class and the value is the value of the property. Given a static property in th

5条回答
  •  庸人自扰
    2020-12-11 22:52

    Here is a function that will get you the names of all static properties in a given type.

    public static IEnumerable GetStaticPropertyNames(Type t) {
      foreach ( var prop in t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ) {
        yield return prop.Name; 
      }
    }
    

    If you want to build up the map of all property names to their values you can do the following

    public static Dictionary GetStaticPropertyBag(Type t) {
      var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
      var map = new Dictionary();
      foreach ( var prop in t.GetProperties(flags) ) {
        map[prop.Name] = prop.GetValue(null,null);
      }
      return map;
    }
    

    Now you can call it with the following

    var bag = GetStaticPropertyBag(typeof(MyResources));
    

提交回复
热议问题