我的枚举无法使用反射和属性信息识别

本文关键字:属性 信息 识别 反射 枚举 我的 | 更新日期: 2023-09-27 17:56:37

我有一个审计类,可以通过反射恢复所有内容。我需要在我的实际点上知道特定属性是否是 Enum,但我得到了一个奇怪的行为:

在每次迭代期间q.PropertyType.IsEnum返回 false。使用快速观察器,该属性确实是错误的,IsClass 也是如此。所以这基本上没什么:)

对这个问题进行了更多研究,我发现可空枚举在IsEnum中返回 false。如何忽略此可为空值并验证该属性是否为枚举?

我的枚举无法使用反射和属性信息识别

当您的属性为空类型时,IsEnum 将返回 false。在这种情况下,在q.PropertyType上调用 Nullable.GetUnderlyingType 将返回所需的类型。然后你可以与IsEnum核实。

编辑:我已经尝试过你的枚举,它是可获取的。 对Foo.GetEnumProperties的调用返回一个包含"TestProp"的数组:

    public enum MyEnum
    {
        [XmlEnumAttribute("Twenty and Something")]
        TwentyTree = 1,
        [XmlEnumAttribute("Thirty and Something")]
        Thirdyfour
    }
    class Foo
    {
        public MyEnum TestProp { get; set; }

        /// <summary>
        /// Get a list of properties that are enum types 
        /// </summary> 
        /// <returns>Enum property names</returns>
        public static string[] GetEnumProperties()
        {
            MemberInfo[] members = typeof(Foo).FindMembers(MemberTypes.Property, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, null);
            List<string> retList = new List<string>();
            foreach (MemberInfo nextMember in members)
            {
                PropertyInfo nextProp = nextMember as PropertyInfo;
                if (nextProp.PropertyType.IsEnum)
                    retList.Add(nextProp.Name);
            } return retList.ToArray();
        }
    }

要做你想做的事情,我使用System.ComponentModel.DescriptionAttribute,然后你可以像这样获取它:

/// <summary>
/// Get the description for the enum
/// </summary>
/// <param name="value">Value to check</param>
/// <returns>The description</returns>
public static string GetDescription(object value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                string desc = attr.Description;
                return desc;
            }
        }
    }
    return value.ToString();
}

无法识别的枚举的一般问题是它们可以为空,然后IsEnum不起作用。
这里就是这种情况,使用 @Skeet 答案检查 C# 中的 Type 实例是否为可为空的枚举,我解决了我的问题。