【发布时间】:2014-09-18 22:48:46
【问题描述】:
我正在使用反射从对象中检索属性的值。该值是一个枚举:
enum MyEnum
{
None,
SomeValue
}
在对象上,属性也有属性
class MyObject
{
[MyAttribute(ExclusionValue = MyEnum.None)]
public MyEnum EnumProperty { get; set; }
}
所以当我谈到事物的反射部分时,我想检查该值是否等于ExclusionValue
// exclusionValue is the value taken from the attribute
// propertyValue is the value retrieved by reflection of the containing object, so at
// this time it just an `object` type.
if(exclusionValue == propertyValue)
{
// Both values are `MyEnum.None` but the if statement never evaluates true.
}
我尝试将exclusionValue 强制转换为一个对象,以便它们都是相同的可见类型
if((object)exclusionValue == propertyValue)
但这也永远不会返回 true。它们绝对是相同的枚举值。此外,我无法在此 if 语句中显式转换任何内容,因为所有不同类型(不仅仅是枚举)的对象中还有许多其他属性需要同样的检查,例如:
class MyObject
{
[MyAttribute(ExclusionValue = MyEnum.None)]
public MyEnum EnumProperty { get; set; }
[MyAttribute(ExclusionValue = false)]
public bool BoolProperty { get; set; }
}
编辑
它们只会是值类型(没有结构)或字符串。
【问题讨论】:
标签: c# reflection enums