Get the value of a constant by name

I have a class with constants. I have a string that can be the same as the name of one of these constants or not.

Thus, a class with constants ConstClasshas some public constlikeconst1, const2, const3...

public static class ConstClass
{
    public const string Const1 = "Const1";
    public const string Const2 = "Const2";
    public const string Const3 = "Const3";
}

To check if the class contains constby name, I tried the following:

var field = (typeof (ConstClass)).GetField(customStr);
if (field != null){
    return field.GetValue(obj) // obj doesn't exists for me
}

I don’t know if this is really the right way to do this, but now I don’t know how to get the value, because the method .GetValueneeds obj type ConstClass(ConstClass is static)

+4
source share
2 answers

, null .

LINQPad , :

void Main()
{
    typeof(Test).GetField("Value").GetValue(null).Dump();
    // Instance reference is null ----->----^^^^
}

public class Test
{
    public const int Value = 42;
}

:

42

, , , .

, , Literal:

LINQPad, :

void Main()
{
    var constants =
        from fieldInfo in typeof(Test).GetFields()
        where (fieldInfo.Attributes & FieldAttributes.Literal) != 0
        select fieldInfo.Name;
    constants.Dump();
}

public class Test
{
    public const int Value = 42;
    public static readonly int Field = 42;
}

:

Value
+8
string customStr = "const1";

if ((typeof (ConstClass)).GetField(customStr) != null)
{
    string value = (string)typeof(ConstClass).GetField(customStr).GetValue(null);
}
+2

Source: https://habr.com/ru/post/1614136/


All Articles