为什么要在 == 上使用 String.Equals? [英] Why would you use String.Equals over ==?
问题描述
我最近接触了一个大型代码库,并注意到所有字符串比较都是使用 String.Equals()
而不是 ==
I recently was introduced to a large codebase and noticed all string comparisons are done using String.Equals()
instead of ==
你认为这是什么原因?
推荐答案
很可能大部分开发人员都来自 Java 背景,其中使用 ==
比较字符串是错误的并且不起作用.
It's entirely likely that a large portion of the developer base comes from a Java background where using ==
to compare strings is wrong and doesn't work.
在 C# 中(对于字符串)没有(实际的)区别,只要它们被输入为字符串即可.
In C# there's no (practical) difference (for strings) as long as they are typed as string.
如果它们被输入为 object
或 T
,那么请在此处查看讨论泛型方法或运算符重载的其他答案,因为在那里您肯定想使用 Equals 方法.
If they are typed as object
or T
then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.
这篇关于为什么要在 == 上使用 String.Equals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!