将两个扩展功能合二为一

时间:2014-04-23 15:11:07

标签: c#

我有两个扩展功能,可在List<int>List<string>上运行。

public static string StringTokenizr(this List<int> list, NpStringTokenizrType type, string splitter = ",")
{
    return string.Join(",", list.ConvertAll(name => string.Format(type == NpStringTokenizrType.StringLike ? "'{0}'" : "{0}", name.ToString().Replace("'", "\\'"))));
}

public static string StringTokenizr(this List<string> list, NpStringTokenizrType type, string splitter = ",")
{
    return string.Join(",", list.ConvertAll(name => string.Format(type == NpStringTokenizrType.StringLike ? "'{0}'" : "{0}", name.ToString().Replace("'", "\\'"))));
}

有没有办法让它更通用,以便它可以只是一个功能?

3 个答案:

答案 0 :(得分:3)

使您的方法通用:

public static string StringTokenizr<T>(
       this List<T> list, 
       NpStringTokenizrType type, 
       string splitter = ",")
{
   return string.Join(",", list.ConvertAll(name => string.Format(type == NpStringTokenizrType.StringLike ? "'{0}'" : "{0}", name.ToString().Replace("'", "\\'"))));
}

答案 1 :(得分:0)

通过这种方式你可以使它一般,但这个函数不会局限于int和字符串它将接受其他类型

public static string StringTokenizr<T>(this List<T> list, NpStringTokenizrType type, string splitter = ",")
{
    return string.Join(",", list.ConvertAll(name => string.Format(type == NpStringTokenizrType.StringLike ? "'{0}'" : "{0}", name.ToString().Replace("'", "\\'"))));
}

答案 2 :(得分:-1)

使用像List<T>这样的泛型类型参数,并检查函数体内的类型,或者将List作为string投射到函数中。