ToString() 在这里是好是坏,还是只是多余?
这两种方法都被编译器接受:
ssMinnow = listStrLineElements[VESSEL_TO_AVOID].ToString();
ssMinnow = listStrLineElements[VESSEL_TO_AVOID];
一种方法比另一种方法更好吗? ToString() 还是不是 ToString(),这就是问题所在。
Both of these are accepted by the compiler:
ssMinnow = listStrLineElements[VESSEL_TO_AVOID].ToString();
ssMinnow = listStrLineElements[VESSEL_TO_AVOID];
Is one way preferable to the other? ToString() or not ToString(), that is the question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它不仅是多余的,而且是危险的:如果
listStrLineElements[VESSEL_TO_AVOID]
恰好为null
,并且使用ToString,您的应用程序将引发异常()
;如果没有ToString()
,它只会将null
分配给ssMinnow
。It is not only redundant, but also is dangerous: if
listStrLineElements[VESSEL_TO_AVOID]
happens to benull
, your application is going to throw an exception if you useToString()
; withoutToString()
, it would simply assignnull
tossMinnow
.如果
listStrLineElements[VESSEL_TO_AVOID]
返回一个字符串,那么是的,它是多余的。如果它返回某种其他类型,那么不,它不是多余的。If
listStrLineElements[VESSEL_TO_AVOID]
returns a string, then yes, it is redundant. if it returns some other type, then no, it is not redundant.一般来说,您不需要调用
ToString()
方法,因为返回的对象类型已经是String
。在您的示例中,我们无法判断,因为
ssMinnow
没有显示声明类型:我假设您使用了var
关键字,它可以与它们或listStrLineElements[ VESSEL_TO_AVOID]
已经返回一个String
in General your don't need to invoke the
ToString()
method is the object type returned is already aString
.in your example we cannot tell that as
ssMinnow
does not show the declaration type :I assume you have usedvar
keyword which will work with both of them orlistStrLineElements[VESSEL_TO_AVOID]
returns already aString
简直是多余。我更喜欢在不需要 ToString() 的地方留下它,但它是一个判断调用。
Simply redundant. I prefer to leave off ToString() where its not needed but its a judgement call.
如果您已经返回字符串,请不要使用 ToString。你只是增加了不必要的开销。
Don't use ToString if you are already returning a string. You're just adding unnecessary overhead.
事情并不像所说的那么简单。可能是多余的;好与坏,见仁见智。由于如果对象在某处被视为字符串,无论如何都会调用 toString(),因此显式使用 toString() 可以作为开发人员阅读代码的路标。显式调用更多地描述了原始意图,而不是将其作为编译器要实现的假设。
It is not so simple as stated. Redundant, possibly; good or bad, a matter of opinion. Since toString() will be called anyway if the object is treated as a string somewhere, the explicit use of toString() can serve as a signpost to the developer reading the code. The explicit call describes more of the original intent than leaving it as an assumption for the compiler to fulfill.