动态获取名称的常量嵌套值

时间:2018-05-14 07:45:07

标签: c#

我有一个存储常量值的类,如下所示

public class FirstClass
{
    public const string A = "AValue";
    public const string B = "BValue";
    public const string C = "CValue";
}

var name = "A";
Console.WriteLine(typeof(FirstClass).GetField(name).GetValue(null)); //AValue

工作得很好,这里的问题,一旦我改变结构以包含嵌套类,我做了这个

public class SecondClass
{
    public class SecondClassOne
    {
        public const string A = "AValue 1";
        public const string B = "BValue 1";
        public const string C = "CValue 1";
    }

    public class SecondClassTwo
    {
        public const string A = "AValue 2";
        public const string B = "BValue 2";
        public const string C = "CValue 2";
    }
}

var className = "SecondClassTwo";
var name = "A";
foreach (Type type in typeof(SecondClass).GetNestedTypes()){
    if(type.Name.Equals(className)){
        Console.WriteLine(type.GetField(name).GetValue(null)); //AValue 2
    }
}

它仍然正常, 但是没有使用for循环来完成所有嵌套类,有没有更好的方法来执行此操作 ?由于列表可能会越来越长,因此将所有这些列表1循环播放似乎并不是很好。

1 个答案:

答案 0 :(得分:6)

当然,只需使用Type.GetNestedType()

var nestedType = typeof(SecondClass).GetNestedType(className);
Console.WriteLine(nestedType.GetField(name).GetValue(null));

但是,如果您经常使用它,我会强烈考虑构建一个字典 - 特别是如果所有常量都是字符串。您最终可能会得到IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>>

public IReadOnlyDictionary<string, IDictionary<string, string>> GetConstants() =>
    typeof(SecondClass).GetNestedTypes()
        .ToDictionary(
            type => type.Name,
            (IReadOnlyDictionary<string, string>) 
            type.GetFields().ToDictionary(f => f.Name, (string) f => f.GetValue(null)));

(目前还没有构建ReadOnlyDictionary,但你当然可以这样做。)

相关问题