.NET反射如何识别返回可空Enum类型的类公共属性?
解决可空枚举的反射识别问题
你的问题出在可空枚举类型的处理上:PurchStatus的属性类型是Nullable<AxdEnum_PurchStatus>(即AxdEnum_PurchStatus?),直接访问prop.PropertyType.BaseType得到的是ValueType,自然无法识别为枚举。
正确的识别方法
需要先提取可空类型的底层实际类型,再判断该类型是否为枚举。可以用Nullable.GetUnderlyingType()方法来处理:
var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && t.Namespace == "MyNamespace" && t.Name == "AxdEntity_PurchTable_1" select t; foreach (var refClass in q.ToList()) { foreach (var prop in refClass.GetProperties()) { if (prop.Name == "PurchStatus") { // 提取可空类型的底层类型,非可空则返回原类型 Type actualPropertyType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; bool isEnum = actualPropertyType.IsEnum; Console.WriteLine($"[{refClass.Name}\\Property\\{prop.Name}]: {actualPropertyType.Name}; {isEnum}"); // 此时输出会是: [AxdEntity_PurchTable_1\Property\PurchStatus]: AxdEnum_PurchStatus; True } } }
扩展:生成枚举的int/string值列表
如果要进一步提取枚举的键值对,可以在识别出枚举类型后,遍历枚举值:
if (actualPropertyType.IsEnum) { Console.WriteLine($"枚举 {actualPropertyType.Name} 的值列表:"); foreach (var enumValue in Enum.GetValues(actualPropertyType)) { int intValue = (int)enumValue; string stringValue = enumValue.ToString(); Console.WriteLine($"- {stringValue}: {intValue}"); } }
这段代码会输出:
枚举 AxdEnum_PurchStatus 的值列表: - None: 0 - Backorder: 1 - Received: 2 - Invoiced: 3 - Canceled: 4
通用化处理(移除指定类和属性的限制)
当你移除Name == "AxdEntity_PurchTable_1"和prop.Name == "PurchStatus"的限制后,就可以批量识别所有包含枚举(含可空枚举)属性的类:
var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && t.Namespace == "MyNamespace" select t; foreach (var refClass in q.ToList()) { foreach (var prop in refClass.GetProperties()) { Type actualType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; if (actualType.IsEnum) { Console.WriteLine($"类 {refClass.Name} 的属性 {prop.Name} 是枚举类型: {actualType.Name}"); // 这里可以添加生成枚举值列表的逻辑 } } }
内容的提问来源于stack exchange,提问作者William YK
相关产品推荐
相关产品推荐

