通过名称获取常量的值

通过名称获取常量的值

本文介绍了通过名称获取常量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有常量的类。我有一些字符串,可以与常量之一相同或不相同。

I have a class with constants. I have some string, which can be same as name of one of that constants or not.

所以常量为 ConstClass 具有一些公共const ,例如 const1,const2,const3 ...

So class with constants ConstClass has some public const like const1, const2, const3...

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

检查类是否包含 const 按名称我已经尝试过下一步:

To check if class contains const by name i have tried next :

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

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

Don't know if it's realy correct way to do that, but now i don't know how to get value, cause .GetValue method need obj of type ConstClass (ConstClass is static)

推荐答案

要使用反射获取字段值或调用静态类型的成员,您可以传递 null 作为实例引用。

To get field values or call members on static types using reflection you pass null as the instance reference.

这是一个简短的程序,它演示:

Here is a short LINQPad program that demonstrates:

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

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

输出:

42

请注意,所示代码不会区分

Please note that the code as shown will not distinguish between normal fields and const fields.

为此,您必须检查字段信息中是否还包含标志 Literal

To do that you must check that the field information also contains the flag Literal:

这是一个简短的LINQPad程序,仅检索常量:

Here is a short LINQPad program that only retrieves constants:

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

这篇关于通过名称获取常量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:58