【问题标题】:Enum array to strings枚举数组到字符串
【发布时间】:2011-02-24 13:30:24
【问题描述】:

我有一个 IEnumerable 的 ToString 扩展方法,它将其转换为字符串列表,如下所示:

    public static string ToString<T>(this IEnumerable<T> theSource,
                                     string theSeparator) where T : class
    {
        string[] array = 
                     theSource.Where(n => n != null).Select(n => n.ToString()).ToArray();

        return string.Join(theSeparator, array);
    }

我现在想对枚举数组做类似的事情:给定 theXStatuses,一个 XStatus 枚举值数组,我想得到一个包含由 theSeparator 分隔的枚举值的字符串。由于某种原因,上述扩展方法不适用于 XStatus[]。所以我尝试了

        public static string ToString1<T>(this IEnumerable<T> theSource,string theSeparator)
                                                                             where T : Enum

但后来我得到一个错误“不能使用...'System.Enum'...作为类型参数约束。

有什么方法可以实现吗?

【问题讨论】:

  • 这是 C#,对吧?您应该将该标签添加到您的问题中(我会这样做,但我不能 100% 确定它是 C#)。

标签: c# enums extension-methods


【解决方案1】:

没有做不到的。最接近的是where T : struct,如果不是枚举,则在函数内部抛出错误。

编辑: 如果您从原始函数中删除where T : class,它也将适用于枚举。 也跳过ToArray() 作为String.Join 接受IEnumerable&lt;string&gt;

【讨论】:

    【解决方案2】:

    Magnus 是对的,不能优雅地做到这一点。可以通过一个小技巧来绕过限制,如下所示:

    public static string ToString<TEnum>(this IEnumerable<TEnum> source,
                                string separator) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum) throw new InvalidOperationException("TEnum must be an enumeration type. ");
        if (source == null || separator == null) throw new ArgumentNullException();
        var strings = source.Where(e => Enum.IsDefined(typeof(TEnum), e)).Select(n => Enum.GetName(typeof(TEnum), n));
        return string.Join(separator, strings);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多