c# – 动态获取名称的常量嵌套值
发布时间:2020-12-16 01:26:51 所属栏目:百科 来源:网络整理
导读:我有一个类存储常量值,如下所示 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))
我有一个类存储常量值,如下所示
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,但你当然可以这样做.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |