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

  • 本文关键字:嵌套 常量 获取 动态 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 循环来遍历所有嵌套类,还有更好的方法可以做到这一点吗?因为列表可能会越来越长,所以逐一循环所有这些列表似乎不是很好。

当然,只需使用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,但你当然可以这样做。

最新更新