关于在字符串上使用.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
}
}我知道最好将null和string.Empty存储为它们的对象类型,但为了这个特定的目的,我需要将它们存储为字符串表示形式:)。
P.P.S.为明确问题而添加匈牙利符号
发布于 2014-02-26 15:59:54
您应该始终支持==而不是Equals。后者是一种基本Object类型的方法,在这种情况下,它将做无用的铸造。
如果要检查string值是空值还是空值,请使用String.IsNullOrEmpty方法。如果,如果您需要采取不同的行动,如果是其中一种或另一种,那么请这样做:
if (value == null)
{
//do stuff
}
else if (value == string.Empty)
{
// do other stuff
}编辑:
正如注释中所指出的,在接收Equals参数的string上有一个重载的string方法。不过,我认为您应该养成使用==的习惯。它只是读起来更好。
发布于 2014-02-26 15:59:50
如果你关心null,你应该使用string.IsNullOrEmpty(),或者string.IsNullOrWhitespace()
https://stackoverflow.com/questions/22046624
复制相似问题