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

标签 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;
    }

我想做一些类似的事情,但是将它应用于列表(而不是字符串列表),但是,编译器无法解析 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;
    }

我错过了什么?

最佳答案

首先,方法声明应该是:

public static string ToCsv<T>(this List<T> list) { // }

注意方法必须参数化;这是 <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(", ");
}

请注意,我已经疯狂地通过接受 IEnumerable<T> 来进一步推广该方法。而不是 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(", ");
}

也就是说,我们不需要转换source.Select(x => x.ToString())的结果。到一个数组。

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

关于c# - 如何将这段代码转换为泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2068747/

相关文章:

Java 泛型 : Cannot convert from Object to T

c# - 如何添加 System.Array 的 .Net C# 类扩展

c# - 返回随机字母表的扩展方法

c# - 在扩展方法中处理 null

c# - OnMouseOver() 不适用于 child

C#:如何声明和使用具有不同类型的泛型类列表?

C# 字符串操作正则表达式或子字符串?

java - Java中特定类型泛型接口(interface)的实现

c# - 尝试调用 function<T> where T : TheClass, new() where T: class

c# - LINQ 返回数组,而不是列表对象的集合