问题
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?
回答1:
toString() is useful whenever you want a string representation of an object. Naturally that happens for debugging purposes, but can also be valid to output results of operations to the user.
For example, let's say you have a Complex class which handles complex numbers. If you want to print them out to an user in a format like 3 + 2i, it is handy if they define toString() as you do not have to write the format every time and the output will be consistent. If you ever want to change that representation, for example to 3 + 2j, you only need to touch the toString() method in the Complex class.
So toString() is not for debugging purposes also, but is a good way to get consistent string representations of your objects.
回答2:
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.
回答3:
My personal preference is that toString() should never be used for anything other than debugging. If you want to produce a string for an object, provide a separate method that clearly documents your intent (getName(), getDescription(), etc). Never rely on the implementation of a toString().
The problem is that many developers see toString() as a debug-level string and think nothing of changing it (say when new fields are added or removed). Heck, some automated toString() builders use reflection to generate a toString() from the fields.
I've found this preference has served me well over the years.
回答4:
All I can say is that I have had code break when I changed the toString of my class to display some additional debug information.
The code in question was a GUI library that decided to use the value of toString as some internal thing (it was a couple of years ago... I forget what it was exactly). The end result was that I didn't use that library anymore.
I would say that since a large group of people see toString as being used for debugging (regardless of your opinion of what it you think it should be used for) that it is problematic to make use of the value returned from it to do anything programmatic (like parse it) or display it to a user.
If you are 100% in control of the toString methods then by all means do what you want.
So, to answer the question, no toString is not only useful for debugging, you can do anything you want with it. However, don't be surprised if toString changes in ways that make you unhappy.
回答5:
In my experience, toString() has little value outside of debugging and logging. You cannot depend on it's format or contents over time, so other than being human readable, don't depend on it for anything other than the simplest of objects (such as the primitive object types). If there are multiple data members, expect they may change in type or number over time, and the output of the toString() along with it.
Another point I would like to strongly make. Do not call other methods in your toString(). Nothing worse than checking the variable contents on a breakpoint in the debugger, and then having more code execute because of method calls in the toString().
回答6:
I think it's important to point out the the people who answered mentioning "toString" notice the lowercase "t" are generally talking about Java, and the people who answered mentioning "ToString" are generally referring to C#. Of course, this doesn't apply to all of the responses.
In my own observation (I use both daily), programmers in C# are encouraged to override "ToString" to display a useful textual representation. Whereas, in Java, I don't see this nearly as much. In fact, I rarely see this.
-JP
回答7:
First, the toString
method should return a human-readable textual representation of the object.
This issue is brought up in Effective Java as Item 10: Always override toString
.
It references the Java API Specification for the Object.toString method:
The result should be a concise but informative representation that is easy for a person to read.
Aside from debugging, overriding the toString
method of a class can be useful when ading objects into a JList or a JTable, which by default will use the toString
method to display the object as a textual form in the list or table.
For example, in my case, I've overridden the toString
method of objects that are added to a JList
so that the user will be able to see information about the item in a list through the GUI.
So, there are indeed cases where the toString
method is useful for cases other than debugging. The key is to have the toString
method return information that is actually useful for a person to see, not the default Object.toString
implementation where the object's memory location is used for its textual representation.
回答8:
Useful for
- Gui (complex Property when you use PropertyGrid, Form header text)
- DataBinding (thats the way how it working)
And any other string output.
回答9:
ToString() is also called by the .NET Framework implicitly when printing any object out to a string.
Console.WriteLine("My Object is" + object.ToString());
is equivalent to
Console.WriteLine("My Object is" + object);
because the ToString() is implicitly called.
I believe, though am not sure, that it is used by the debugger for the "value" of an object. This can be fairly handy, though limited. In most cases writing your own debugger visualizer would be a better idea.
回答10:
On AS3, I had to convert a 2D array into a 1D array. The fastest (run speed) and easiest (coding time) solution was:
var new1DArray:Array = the2DArray.toString().split(",");
Be surprised but it's actually working as intended and quite fast, too!
回答11:
I use ToString() a ton for datetime formats.
http://hunterconcepts.com/content/tools/formats/
回答12:
Aside from what everyone else has already said, overriding ToString() is also useful when using controls that call it. For example, a ComboBox:
myComboBox.Items.Add(new MyClass());
// now, whatever ToString() returns is shown in the
// ComboBox, but you can get the object back by through
// the SlectedItem property.
回答13:
it might not be the "intented" use but I've used it for data serialization
storeToHardDrive(studentList.ToString());
来源:https://stackoverflow.com/questions/563676/is-tostring-only-useful-for-debugging