开发者

Question regarding C#'s `List<>.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.ToS开发者_JAVA技巧tring 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.

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.

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);


I think the reason is, that it is unclear what it should actualy do.

Maybe do ToString on ever elemenat and separate them with comas? But what if someone wants semicolons? Or dashes? Or someone wants to enclose whole string in curly or normal braclets? Or somone wants to use different function to get textual representation of single element?

Few things to note: ToString should be used only for debuging purpouses. If you want to export your data into string, either override this behaviour in your class or make an utility class for it.

Also List is intended to store elements, not to provide their textual representation.


Because it's probably not that easy to implement.

A List<> can contain a lot of stuff. For example another List<> that contains a Dictionary<> that contains complex objects...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜