通过名称获取常量的值

Get value of constant by name

我有一个带有常量的 class。我有一些字符串,它可以与其中一个常量的名称相同,也可以不相同。

所以 class 和常量 ConstClass 有一些 public constconst1, const2, const3...

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

要检查 class 是否按名称包含 const 我接下来尝试了:

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

不知道这样做是否真的正确,但现在我不知道如何获取值,因为 .GetValue 方法需要 ConstClass 类型的对象(ConstClass 是静态的)

要使用反射获取字段值或调用静态类型的成员,您将 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
string customStr = "const1";

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