如何将这段代码转换为泛型?

Ang*_*ker 3 c# generics extension-methods

我有以下扩展方法,它接受List并将其转换为逗号分隔的字符串:

    static public string ToCsv(this List<string> lst)
    {
        const string SEPARATOR = ", ";
        string csv = string.Empty;

        foreach (var item in lst)
            csv += item + SEPARATOR;

        // remove the trailing separator
        if (csv.Length > 0)
            csv = csv.Remove(csv.Length - SEPARATOR.Length);

        return csv;
    }
Run Code Online (Sandbox Code Playgroud)

我想做一些类似的事情,但将它应用于List(而不是List of String),但是,编译器无法解析T:

    static public string ToCsv(this List<T> lst)
    {
        const string SEPARATOR = ", ";
        string csv = string.Empty;

        foreach (var item in lst)
            csv += item.ToString() + SEPARATOR;

        // remove the trailing separator
        if (csv.Length > 0)
            csv = csv.Remove(csv.Length - SEPARATOR.Length);

        return csv;
    }
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

jas*_*son 8

首先,方法声明应该是:

public static string ToCsv<T>(this List<T> list) { // }
Run Code Online (Sandbox Code Playgroud)

注意,该方法必须参数化; 这是<T>方法名称之后.

其次,不要重新发明轮子.只需使用String.Join:

public static string ToCsv<T>(this IEnumerable<T> source, string separator) {
    return String.Join(separator, source.Select(x => x.ToString()).ToArray());
}

public static string ToCsv<T>(this IEnumerable<T> source) {
    return source.ToCsv(", ");
}
Run Code Online (Sandbox Code Playgroud)

请注意,我已经疯狂了,并通过接受IEnumerable<T>而不是a来进一步概括该方法List<T>.

在.NET 4.0中,您将能够说:

public static string ToCsv<T>(this IEnumerable<T> source, string separator) {
    return String.Join(separator, source.Select(x => x.ToString());
}

public static string ToCsv<T>(this IEnumerable<T> source) {
    return source.ToCsv(", ");
}
Run Code Online (Sandbox Code Playgroud)

也就是说,我们不需要将结果转换为source.Select(x => x.ToString())数组.

最后,有关此主题的有趣博客文章,请参阅Eric Lippert的帖子Comma Quibbling.


Kev*_*ose 7

尝试将声明更改为

static public string ToCsv<T>(this List<T> lst){ ...
Run Code Online (Sandbox Code Playgroud)