0

看看这个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();
}

还有一个enum带有Description属性的例子:

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()扩展方法) .

4

1 回答 1

3

Colors即使没有定义值,您也可以创建类型变量:

public enum Colors { }

var color2 = (Colors)100; // with casting
Colors color2 = default; // default value '0'
于 2018-07-19T14:46:54.030 回答