如何将这段代码转换为泛型?
我有以下扩展方法,它接受 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 (而不是字符串列表),但是,编译器无法解析 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;
}
我缺少什么?
I have the following extension method that takes a List and converts it to a comma separated string:
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;
}
I want to do something analogous but apply it to a List (instead of List of String) , however, the compiler can't resolve for 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;
}
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,方法声明应该是:
注意方法必须是参数化的;这是方法名称后面的
。其次,不要重新发明轮子。只需使用
String.Join
< /a>:请注意,我已经疯狂地通过接受
IEnumerable
而不是List
来进一步概括该方法。在 .NET 4.0 中,您可以说:
也就是说,我们不需要将
source.Select(x => x.ToString())
的结果转换为数组。最后,有关此主题的有趣博客文章,请参阅 Eric Lippert 的文章 逗号狡辩。
First, the method declaration should be:
Note that the method must be parameterized; this is the
<T>
after the name of the method.Second, don't reinvent the wheel. Just use
String.Join
:Note that I've gone hog wild and generalized the method further by accepting an
IEnumerable<T>
instead of aList<T>
.In .NET 4.0 you will be able to say:
That is, we do not require to convert the result of
source.Select(x => x.ToString())
to an array.Finally, for an interesting blog post on this topic, see Eric Lippert's post Comma Quibbling.
尝试将声明更改为
Try changing the declaration to
您的函数需要一个通用参数:
Your function needs a generic parameter:
您可以使其更通用并使用 IEnumerable 而不是 List< T >,毕竟您没有使用任何特定于列表的方法
You could make this more generic and use IEnumerable instead of a List< T >, after all you are not using any list-specific methods