gpt4 book ai didi

c# - List.Contains(mystring) 是做引用比较还是值比较?

转载 作者:行者123 更新时间:2023-11-30 13:16:17 26 4
gpt4 key购买 nike

List.Contains(mystring) 是做引用比较还是值比较?例如我有这段代码:

/// <summary>
/// If the value isn't null or an empty string,
/// and doesn't exist in the list, it adds it to the list
/// </summary>
static void AddToListIfNotEmpty(List<string> thelist, SqlString val)
{
string value = val.ToString().Trim();
if (!string.IsNullOrEmpty(value))
{
bool found = false;
foreach (string x in thelist) if (x == value) found = true;
if (!found) thelist.Add(value);
}
}

我可以将 foreach 和以下行简化为:

if (!thelist.Contains(value)) thelist.Add(value);

谢谢

最佳答案

IList<T>使用 Comparator<T>.Default进行比较,然后按 String 的值进行比较对象。

如果你愿意,你可以将你的项目移动到 IDictionary<T, bool>或类似的东西,您可以在其中指定您的 IComparator - 指定一个检查引用。 (即使在那种情况下,你最好使用 foreach 循环)

如果您可以使用 LINQ,您也可以在那里创建一个带有引用比较的语句。

关于c# - List<String>.Contains(mystring) 是做引用比较还是值比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1264223/

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