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

Dea*_*ean 3 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
Run Code Online (Sandbox Code Playgroud)

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

它仍然工作正常,但没有使用for循环来通过所有嵌套类,有没有更好的方法来做到这一点?因为列表可能会越来越长,所以将所有这些列表1逐个循环似乎并不是很好.

Jon*_*eet 6

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

var nestedType = typeof(SecondClass).GetNestedType(className);
Console.WriteLine(nestedType.GetField(name).GetValue(null));
Run Code Online (Sandbox Code Playgroud)

但是,如果您经常使用它,我会强烈考虑构建一个字典 - 特别是如果所有常量都是字符串.你最终可能得到一个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)));
Run Code Online (Sandbox Code Playgroud)

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

  • @Dean:我不确定你的意思是"无法控制常量列表" - 我建议用基于现有类的反射来构建它.这是在执行时访问它的一种不同方式,就是这样. (3认同)