我有一个审计类,通过反射恢复一切。我需要在我的实际知道如果一个特定的属性是一个枚举,但我得到一个奇怪的行为:我的枚举不被识别使用反射和PropertyInfo
在foreach迭代q.PropertyType.IsEnum
返回false。并且使用Quick观察器,该属性是非常错误的,而IsClass也是如此。所以这是基本上没有:)
学习一点关于这个问题我发现Nullable Enum在IsEnum
返回false。我怎样才能忽略这个可空对象并验证属性是否是一个枚举?
我有一个审计类,通过反射恢复一切。我需要在我的实际知道如果一个特定的属性是一个枚举,但我得到一个奇怪的行为:我的枚举不被识别使用反射和PropertyInfo
在foreach迭代q.PropertyType.IsEnum
返回false。并且使用Quick观察器,该属性是非常错误的,而IsClass也是如此。所以这是基本上没有:)
学习一点关于这个问题我发现Nullable Enum在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回答Checking if Type instance is a nullable enum in C#我解决了我的问题。
Nit:从30-39的数字拼写为“三十”,而不是“第三”。 – 2011-05-17 19:40:43
@JS邦,请重点关注。 :D – Custodio 2011-05-17 19:43:24
@Custódio什么是ReflectionUtil? – 2011-05-17 19:46:05