如何从类型变量中获取枚举的默认值
How to get default value of an enum from a type variable
给定一个对象(在设计时未知),我循环其属性以执行一些过程。在每个 属性 上,我必须检查它的值是否与默认值不同。
foreach(var p in propertyInfos)
{
if (something) { ... }
else if (p.PropertyType.IsEnum)
{
object oDefault = GetDefaultValueOfThisPropertyByWhateverMethod();
if (oDefault == null)
oDefault = default(p.PropertyType); // not valid
var vValue = p.GetValue(myObject);
if (!oDefault.Equals(vValue))
// Do something enum specific when value is not the default one.
}
}
知道可能存在不包含值为 0 的项目的枚举,我怎么能做到这一点?
enum
的默认值为 0... 即使没有为 0 定义任何值。最后你总是可以 (EnumType)123
任何 enum
。 enum
不要 check/restrict 他们的 "valid" 价值观。只给一些特定的值一些标签。
注意我之前说的0是一个"typed"值...所以是(EnumType)0
,不是(int)0
...你可以:
object oDefault = Enum.ToObject(p.PropertyType, 0);
甚至适用于非int
枚举,例如:
enum MyEnum : long
{
}
显然你甚至可以:
object oDefault = Activator.CreateInstance(p.PropertyType);
因为 new SomeEnumType()
是 0。
给定一个对象(在设计时未知),我循环其属性以执行一些过程。在每个 属性 上,我必须检查它的值是否与默认值不同。
foreach(var p in propertyInfos)
{
if (something) { ... }
else if (p.PropertyType.IsEnum)
{
object oDefault = GetDefaultValueOfThisPropertyByWhateverMethod();
if (oDefault == null)
oDefault = default(p.PropertyType); // not valid
var vValue = p.GetValue(myObject);
if (!oDefault.Equals(vValue))
// Do something enum specific when value is not the default one.
}
}
知道可能存在不包含值为 0 的项目的枚举,我怎么能做到这一点?
enum
的默认值为 0... 即使没有为 0 定义任何值。最后你总是可以 (EnumType)123
任何 enum
。 enum
不要 check/restrict 他们的 "valid" 价值观。只给一些特定的值一些标签。
注意我之前说的0是一个"typed"值...所以是(EnumType)0
,不是(int)0
...你可以:
object oDefault = Enum.ToObject(p.PropertyType, 0);
甚至适用于非int
枚举,例如:
enum MyEnum : long
{
}
显然你甚至可以:
object oDefault = Activator.CreateInstance(p.PropertyType);
因为 new SomeEnumType()
是 0。