关于在字符串上使用.Equals()
或==
字符串,这是关于检查string.Empty
和null
对象的问题。
在比较string.Empty
和null
对象时,应该使用==
还是应该使用.Equals()
?
// Add vars to instance variables
for (int i = 0; i < paramFirstList.Count; i++)
{
// if the key is null, replace it
// with a "null" string
if (paramFirstList[i] == null)
{
_firstList.Add("null");
}
else if (paramFirstList[i] == string.Empty)
{
_firstList.Add("empty");
}
else
{
// Do something
}
}
PS我知道这是更好地存储null
并string.Empty
作为他们的对象类型,但对于这个特定的目的,它是在我的要求将它们存储为一个字符串表示:)。
PPS为清楚起见增加了匈牙利符号
您应该始终偏爱==而不是Equals
。后者是基本Object
类型的方法,在这种情况下将进行无用的转换。
如果要检查string
值是否为null或为空,请使用String.IsNullOrEmpty
method。如果相反,如果您需要采取不同的行动,请执行以下操作:
if (value == null)
{
//do stuff
}
else if (value == string.Empty)
{
// do other stuff
}
编辑:
正如在评论中指出存在是一个重载Equals
上的方法string
,其接收string
参数。不过,我认为您应该养成使用==的习惯。它读起来更好,恕我直言。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句