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 ?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,396 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,676 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,188 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,277 questions
{count} votes

Accepted answer
  1. shiva patpi 13,141 Reputation points Microsoft Employee
    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