Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - Is toString() only useful for debugging?

Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.


EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, the key is that you're supposed to override the default implementation of ToString() to make it useful. ToString() can be a great way to output the value of something back to the UI.

A simple example would be if you have a Name class with a three strings (First, Middle, Last). You can have a ToString() method that formats it for the UI: "Last, First Middle" for example.

Or a class that stores a mathematical operation (values Left=2, Right=3, Result=6 and an operator enum=Multiply). Call ToString() to get "2 * 3 = 6".

However, it is probably more common to have a variety of different To<qualifier>String() methods, like the .NET DateTime class. (ToShortDateString(), ToLongDateString(), ToLongTimeString(), ...)

Edit: As for why it's rooted at the Object class, it's simply because ToString() is a valid operation for anything.

Additionally, strings can be a good way of marshaling between data types or data consumers, because it's (practically) guaranteed to be parsable and doesn't require extra encoding or care.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...