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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…