how to get all static members inside a class?

兰树豪 381 Reputation points
2023-03-22T04:00:04.1733333+00:00

lUser's image

let's say we have a class "MyClass", now i want to put all static menbers into a Dictionary ,

use name "a", "b", "c", "d" as key, use "aaa", "bbb", "ccc", ”ddd“ as value.

Can it be done ?

Developer technologies | Windows Presentation Foundation
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. shiva patpi 13,366 Reputation points Microsoft Employee Moderator
    2023-03-22T05:37:16.44+00:00

    Hello @兰树豪,

    Can you try below code:

    Type myType = typeof(MyClass);
    
                // Get all static members of MyClass
                FieldInfo[] staticFields = myType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                // Display the names of all static members
                Dictionary<string,string> map = new Dictionary<string,string>();
                foreach (FieldInfo field in staticFields)
                {
                    object value = field.GetValue(null);
                    map.Add(field.Name, value.ToString());
                }
    
                foreach(string key in map.Keys) {
                    Console.WriteLine("{0}={1}",key, map[key].ToString());
                }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.