加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将这段代码转换为Generics?

发布时间:2020-12-15 19:49:05 所属栏目:百科 来源:网络整理
导读:我有以下扩展方法,它接受List并将其转换为逗号分隔的字符串: static public string ToCsv(this Liststring lst) { const string SEPARATOR = ","; string csv = string.Empty; foreach (var item in lst) csv += item + SEPARATOR; // remove the trailing
我有以下扩展方法,它接受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;
    }

我想做一些类似的事情,但将它应用于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;
    }

我错过了什么?

解决方法

首先,方法声明应该是:

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,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读