我有一个类存储常量值,如下所示 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).Ge
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逐个循环似乎并不是很好.
当然,只需使用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,但你当然可以这样做.)