C#中如何使用GetProperty获取静态类常量值
错误原因
ABC是Constants下嵌套类HostServer的成员,不是Constants的直接成员,无法直接从Constants类型查询到ABC是字段,不是属性,调用GetProperty方法无法匹配到字段类型的成员const修饰的常量本质也是静态字段,同样需要用获取字段的方式取值
可运行的正确实现
using System; public static class Constants { public static class HostServer { public static string ABC = "abc.com"; } public static class WMS { public const string URL = "/create/user"; } } public class Program { public static void Main() { Console.WriteLine("Hello World"); // 第一步:获取嵌套类HostServer的类型 Type hostServerType = typeof(Constants).GetNestedType("HostServer"); // 第二步:获取ABC字段 var abcField = hostServerType.GetField("ABC"); // 第三步:获取静态字段值,静态成员传null即可 string x = abcField.GetValue(null).ToString(); Console.WriteLine(x); // 输出abc.com // 也可以用通用方法获取WMS.URL string url = GetConstantValue("WMS.URL").ToString(); Console.WriteLine(url); // 输出/create/user } /// <summary> /// 通用获取Constants下嵌套类常量/静态字段的方法 /// </summary> /// <param name="fullName">嵌套类名.字段名,比如HostServer.ABC</param> /// <returns>字段值</returns> public static object GetConstantValue(string fullName) { string[] parts = fullName.Split('.'); if (parts.Length != 2) throw new ArgumentException("参数格式需为 嵌套类名.字段名"); Type nestedType = typeof(Constants).GetNestedType(parts[0]); if (nestedType == null) throw new ArgumentException($"不存在嵌套类:{parts[0]}"); var field = nestedType.GetField(parts[1]); if (field == null) throw new ArgumentException($"嵌套类{parts[0]}中不存在字段:{parts[1]}"); return field.GetValue(null); } }
补充说明
- 如果需要支持非public成员、不区分大小写匹配,可以在
GetNestedType、GetField方法中传入BindingFlags参数调整匹配规则,示例:GetNestedType("hostserver", BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase) - 所有静态成员、const常量通过反射取值时,
GetValue的实例参数都传null即可
内容的提问来源于stack exchange,提问作者S Deepakkumar
相关产品推荐
相关产品推荐

