何时使用toString()方法 [英] when to use toString() method
问题描述
这听起来很基本......有人可以解释一下使用 toString()
方法以及何时有效地使用它?
This may sound very basic... can someone please explain the use of the toString()
method and when to effectively use this?
在Google上搜索过但找不到任何好的资源。
Have done a search on google but could not find any good resource.
推荐答案
在大多数语言中, toString
或等效方法只保证对象可以用文本表示。
In most languages, toString
or the equivalent method just guarantees that an object can be represented textually.
这对于日志记录特别有用,调试或任何其他需要能够将您遇到的任何对象呈现为字符串的情况。
This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.
对象通常实现自定义 toString
行为,以便该方法实际上告诉您有关对象实例的信息。例如, Person
类可能会覆盖它以返回姓氏,名字,而日期
类将显示根据某些默认设置(例如当前用户界面文化)格式化的日期。
Objects often implement custom toString
behavior so that the method actually tells you something about the object instance. For example, a Person
class might override it to return "Last name, First name" while a Date
class will show the date formatted according to some default setting (such as the current user interface culture).
这篇关于何时使用toString()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!