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/