【问题标题】:Get value of constant by name按名称获取常量的值
【发布时间】:2016-02-02 07:25:39
【问题描述】:

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

所以带有常量ConstClass 的类有一些public constconst1, const2, const3...

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

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

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

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

【问题讨论】:

  • 能否请您重新组织您的问题,并显示您的代码,以便更容易理解? (而不是描述你的代码,这很难遵循)
  • 我强烈建议不要使用一些常量和反射来获取它们,而是使用Dictionary<string, string>。这样更高效、更易维护、更易读。

标签: c# field constants


【解决方案1】:

要使用反射获取字段值或调用静态类型的成员,您需要传递 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

【讨论】:

  • 这很有帮助,但我不得不对其进行一些调整,因为我的函数传入了 Type 参数。我的实现类似于(myPassedType as Type).GetField("Value").GetValue(null)
【解决方案2】:
string customStr = "const1";

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

【讨论】:

  • 你会解释你的代码以及如何解决这个问题吗?
  • 不,不是真的,这是不言自明的。 OP 询问如何获取 const 变量的值,这就是答案。
  • 字符串 customStr = "const1";不包括 'const' 关键字,因此它不是常量变量。因此,无论是否不言自明,这都不是问题的答案。
  • @vynsane, customStr 包含常量名称,需要其值。
猜你喜欢
  • 2014-02-08
  • 2013-09-16
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多