根据你的容器中的内容来定。等下贴代码示例
using System;
using System.Collections.Generic;
namespace Test_zhidao
{
class A{
public int a;
#region Equals and GetHashCode implementation
public override bool Equals(object obj)
{
A other = obj as A;
if (other == null)
return false;
return this.a == other.a;
}
public override int GetHashCode()
{
int hashCode = 0;
unchecked {
hashCode += 1000000007 * a.GetHashCode();
}
return hashCode;
}
public static bool operator ==(A lhs, A rhs)
{
if (ReferenceEquals(lhs, rhs))
return true;
if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
return false;
return lhs.Equals(rhs);
}
public static bool operator !=(A lhs, A rhs)
{
return !(lhs == rhs);
}
#endregion
}
class B{
public int b;
}
class Program
{
public static void Main(String[] args)
{
List list_a = new List();
A obja1 = new A();
obja1.a = 100;
A obja2 = new A();
obja2.a = 100;
list_a.Add(obja1);
Console.WriteLine(list_a.Contains(obja2));//True
List list_b = new List();
B objb1 = new B();
objb1.b = 100;
B objb2 = new B();
objb1.b = 100;
list_b.Add(objb1);
Console.WriteLine(list_b.Contains(objb2));//False
Console.ReadKey(true);
}
}
}
也就是说,这个是根据类的Equals方法来定的,而object 顶级类,是以地址比较为准的,你的子类如果不重载,那么就比较地址,如果你重载了,就按照你指定的方式来比较。
Contains方法的源码如下,比较的是值
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
路过,学习中