【问题标题】:Could GetMember() ever return an empty array for an enum?GetMember() 可以为枚举返回一个空数组吗?
【发布时间】: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 &lt; 1) 检查是否必要?从GetMember() 返回的数组对于enum 会不会是空的?我知道你可以像这样声明一个空的enum

public enum Colors
{
}

但是我不知道你是否甚至可以创建一个Colors类型的变量然后......

var green = Colors. // What goes here?

我想删除if (memberInfo.Length &lt; 1) 检查,但如果以后会引起问题,我不想这样做(我想不出我需要一个空的enum 的原因,但是其他开发者可能会使用GetDescription() 扩展方法)。

【问题讨论】:

  • Colors green = default 有效。
  • @AlessandroD'Andria 由于枚举继承自某种整数类型,默认值将与 0 相同,并且在大多数情况下(未指定值时)它将返回第一个值。您发布的代码将等同于 Blue
  • @Fabulous 当Colors 是一个空枚举时不会。我刚刚对其进行了测试,@AlessandroD'Andria 是正确的,如果if (memberInfo.Length &lt; 1) 检查不存在,它会抛出一个IndexOutOfRangeException。 :(
  • 第一个enum声明等于Blue,但第二个public enum Colors { }不等于。
  • Colors green = (Colors)1000 也是如此。枚举可以包含与 .NET 中的基类型兼容的任何值

标签: c# enums attributes system.componentmodel


【解决方案1】:

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

public enum Colors { }

var color2 = (Colors)100; // with casting
Colors color2 = default; // default value '0'

【讨论】:

  • 然后检查保持不变。谢谢!
  • 经常被遗忘的东西:即使是负整数也是有效整数:(Colors)(-100) :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
相关资源
最近更新 更多