按名称获取常量的值

Get value of constant by name(按名称获取常量的值)

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

问题描述

我有一个带常量的类.我有一些字符串,可以与其中一个常量的名称相同或不同.

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

所以类 ConstClass 有一些 public 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(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.

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

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

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

本文标题为:按名称获取常量的值

基础教程推荐