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);
谢谢
SqlString
引用不可能等于已经在列表中的string
? - ThorarinString
类的等号操作符是按值比较而不是按引用比较的。如果要比较引用,您需要先将其转换为object
。 - Thorarin