有关C#的`List<> .ToString`的问题 [英] Question regarding C#'s `List<>.ToString`

查看:81
本文介绍了有关C#的`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>类似,它不会覆盖GetHashCodeEquals.请注意,除了调用简单的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&lt;&gt; .ToString`的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆