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

标签 c# string

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/

相关文章:

c# - foreach 循环无法转换但手动转换和 for 循环工作

c# - 从字符串中删除文本,直到到达某个字符

html - 让 HTML 识别\n 和\t

将字符串转换为 double 或 float 以执行数学方程式

regex - 在第一个冒号处分割字符串

c# - 在 C# 中将子字符串与给定的字符串分开

c# - 反转字符串中的任何一组数字

c# - XML 输出顺序错误

c# - 如果 ConfigurAwait 设置为 False,任务不会进入故障状态

c# - 功能构成