开发者

Enum array to strings

I have a ToString extension method of an IEnumerable, which converts it to a list of strings as follows:

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

I now want to do something similar with an array of enums: given theXStatuses, an array of XStatus enum values, I want to get a string containing the enum values separatd by theSeparator. For some reason, the above extension method doesn't work for XStatus[]. So I tried

        public static string ToString1<T>(this IEnumerable<T> theSource,string theSeparator)
                                                                             where 开发者_StackOverflow中文版T : Enum

But then I got an error that "cannot use ... 'System.Enum'...as type parameter constraint.

Is there any way to achive this?


No cant be done. The closest would be where T : struct and than throw error inside function if not Enum.

Edit: If you remove where T : class from your original function it will work on enums also. Also skip the ToArray() as String.Join takes in IEnumerable<string>


Magnus is right, it can't be done, elegantly. The limitation can be circumvented with a small hack, like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜