简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM