枚举数组到字符串

时间:2011-02-24 13:30:25

标签: c# enums extension-methods

我有一个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);
    }

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

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

但后来我收到一条错误“无法使用......'System.Enum'...作为类型参数约束。

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:4)

不能做。最接近的是where T : struct,如果不是Enum,则在函数内抛出错误。

修改 如果您从原始功能中删除where T : class,它也可以在枚举中使用。 也可以跳过ToArray()作为String.Join接收IEnumerable<string>

答案 1 :(得分:1)

马格努斯是对的,它不能做到,优雅。这种限制可以通过一个小的黑客来规避,如下:

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);
}