按名称

时间:2015-11-02 12:03:15

标签: c# field const

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

所以具有常量ConstClass的类有一些public const,如const1, 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方法需要类型{{1}的obj (ConstClass是静态的)

2 个答案:

答案 0 :(得分:13)

要使用反射获取字段值或在静态类型上调用成员,请将prepared.executeUpdate(); 作为实例引用传递。

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

null

输出:

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

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

请注意,所示代码不区分普通字段和常量字段。

为此,您必须检查字段信息是否还包含标记42

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

Literal

输出:

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;
}

答案 1 :(得分:3)

string customStr = "const1";

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