【发布时间】:2018-07-19 14:33:34
【问题描述】:
看看这个enum扩展方法获取Description属性:
public static string GetDescription(this Enum enumValue)
{
var memberInfo = enumValue.GetType().GetMember(enumValue.ToString());
if (memberInfo.Length < 1)
return null;
var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? ((DescriptionAttribute)attributes[0]).Description : enumValue.ToString();
}
还有一个带有Description 属性的enum 示例:
public enum Colors
{
[Description("Navy Blue")]
Blue,
[Description("Lime Green")]
Green
}
最后是扩展方法的使用:
var blue = Colors.Blue;
Console.WriteLine(blue.GetDescription());
// Console output: Navy Blue
我的问题是,对于enums,if (memberInfo.Length < 1) 检查是否必要?从GetMember() 返回的数组对于enum 会不会是空的?我知道你可以像这样声明一个空的enum:
public enum Colors
{
}
但是我不知道你是否甚至可以创建一个Colors类型的变量然后......
var green = Colors. // What goes here?
我想删除if (memberInfo.Length < 1) 检查,但如果以后会引起问题,我不想这样做(我想不出我需要一个空的enum 的原因,但是其他开发者可能会使用GetDescription() 扩展方法)。
【问题讨论】:
-
Colors green = default有效。 -
@AlessandroD'Andria 由于枚举继承自某种整数类型,默认值将与 0 相同,并且在大多数情况下(未指定值时)它将返回第一个值。您发布的代码将等同于 Blue
-
@Fabulous 当
Colors是一个空枚举时不会。我刚刚对其进行了测试,@AlessandroD'Andria 是正确的,如果if (memberInfo.Length < 1)检查不存在,它会抛出一个IndexOutOfRangeException。 :( -
第一个
enum声明等于Blue,但第二个public enum Colors { }不等于。 -
Colors green = (Colors)1000也是如此。枚举可以包含与 .NET 中的基类型兼容的任何值
标签: c# enums attributes system.componentmodel