Examples of reading static class constant properties and values

Posted on

1. Background

Recently, there is a requirement in the project to find the corresponding name of the value from the value entered by the user. Because other modules have defined a set of constants from name to value, they want to borrow the definition.

2. Implementation

The idea of implementation is to use reflection supported by C #.

First of all, the definition of constant attribute in static class is given as follows.

public static class FruitCode
public const int Apple = 0x00080020;
public const int Banana = 0x00080021;
public const int Orange = 0x00080022;

Secondly, write a method to extract the static class constant name and value, as shown below.

Type t = typeof(FruitCode);
Fieldinfo [] FIS = t.getfields(); // note that you can't have any options here, otherwise you won't be able to get the const constant
Dictionary<int, string> dicFruitCode = new Dictionary<int, string>();
foreach (var fieldInfo in fis)
var codeValue = fieldInfo.GetRawConstantValue();
dicFruitCode.Add(Convert.ToInt32(codeValue), fieldInfo.Name.ToString());

foreach(var item in dicFruitCode)

As scheduled, the required purpose has been achieved, as shown in the figure.

Here is the article about C # reading static class constant properties and values. For more information about C # reading static class constant properties and values, please search previous articles of developer or continue to browse the following articles. I hope you can support developer more in the future!

Leave a Reply

Your email address will not be published.