toString()只对调试有用吗?

编程入门 行业动态 更新时间:2024-10-28 18:31:55
本文介绍了toString()只对调试有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

除了当然,它们与原语一起使用。我看到的大多数(如果不是全部)实现仅从程序员的角度来看是有用的。

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

EDIT :我知道我应该覆盖默认行为,这就是为什么我提到实现:)。而且我确实得到了在GUI中需要字符串表示的一些组件中覆盖它的价值。但是,至少在JDK中,我看到很多的实现只在你需要调试对象实例时才会使用。

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.

为什么它是否植根于Object类,因为它只对GUI /调试工具有用吗?还有其他用途我不知道吗?

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?

推荐答案

toString()在你想要一个对象的字符串表示时很有用。当然,这是出于调试目的,但也可以有效地将操作结果输出给用户。

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.

例如,假设您有一个处理复数的Complex类。如果你想以 3 + 2i 的格式将它们打印给用户,如果它们定义toString()就很方便,因为你不必每次都写入格式,输出就是是一致的。如果您想要更改该表示形式,例如更改为 3 + 2j ,则只需要触摸Complex类中的toString()方法。

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.

所以toString()也不是为了调试目的,而是获得对象的一致字符串表示的好方法。

So toString() is not for debugging purposes also, but is a good way to get consistent string representations of your objects.

更多推荐

toString()只对调试有用吗?

本文发布于:2023-11-05 14:48:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只对   有用吗   toString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!