gpt4 book ai didi

c# - 在空值和 string.Empty 上使用 == 或 .Equals()

转载 作者:行者123 更新时间:2023-11-30 14:10:52 25 4
gpt4 key购买 nike

关于在字符串上使用 .Equals()==,这里有一个关于检查 string.Empty 的问题和 null 对象。

在比较 string.Emptynull 对象时,我应该使用 == 还是应该使用 .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
}
}

附言我知道最好将 nullstring.Empty 存储为它们的对象类型,但出于这个特定目的,我的要求是将它们存储为字符串表示形式:) .

附言为了问题的清晰度添加了匈牙利符号

最佳答案

你应该总是喜欢 == 而不是 Equals。后者是基本 Object 类型的方法,在这种情况下将执行无用的转换。

如果你想检查一个 string 值是 null 还是空的,使用 String.IsNullOrEmpty方法。相反,如果您需要采取不同的行动,那么请执行以下操作:

if (value == null)
{
//do stuff
}
else if (value == string.Empty)
{
// do other stuff
}

编辑:

正如评论中所指出的, string 上的重载 Equals 方法,该方法接收 string范围。不过,我认为您应该养成使用 == 的习惯。恕我直言,它只是读起来更好。

关于c# - 在空值和 string.Empty 上使用 == 或 .Equals(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22046624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com