有关C#的`List<> .ToString`的问题 [英] Question regarding C#'s `List<>.ToString`
问题描述
为什么C#List<>
的ToString
方法不提供明智的字符串表示形式来打印其内容?当我尝试打印List<>
对象时,我得到了类名(我假设它是默认的object.ToString
实现).为什么会这样?
Why doesn't C# List<>
's ToString
method provide a sensible string representation that prints its contents? I get the class name (which I assume is the default object.ToString
implementation) when I try to print a List<>
object. Why is that so?
推荐答案
简单的答案是:恐怕就是这样.
The simple answer is: that's just the way it is, I'm afraid.
与List<T>
类似,它不会覆盖GetHashCode
或Equals
.请注意,除了调用简单的ToString
本身(可能用逗号分隔值)之外,它几乎没有其他令人愉悦的格式化方式.
Likewise List<T>
doesn't override GetHashCode
or Equals
. Note that it would have very little way of formatting pleasantly other than to call the simple ToString
itself, perhaps comma-separating the values.
如果愿意,您总是可以编写自己的扩展方法来执行适当的格式设置,或者使用string.Join
的较新的重载使其变得非常简单:
You could always write your own extension method to perform appropriate formatting if you want, or use the newer overloads of string.Join
which make it pretty simple:
string text = string.Join(",", list);
这篇关于有关C#的`List<> .ToString`的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!