这是我的班级:
public class MyClass
{
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
}
然后我有两个相似的列表:
List list1 = new List()
{
new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
List list2 = new List()
{
new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
问题是NUnit CollectionAssert总是返回false.
CollectionAssert.AreEqual(list1,list2);
我错过了一些关于CollectionAssert测试的内容
在AreEqual
为对象的平等检查.由于您没有覆盖该Equals
方法,因此false
如果引用不相等,它将返回.
你可以通过覆盖Equals
你的方法来解决这个问题MyClass
:
public class MyClass { public string Name { get; set; } public string FaminlyName { get; set; } public int Phone { get; set; } public override bool Equals (object obj) { MyClass mobj = obj as MyClass; return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone); } }
您还可以更好地覆盖该GetHashCode
方法:
public class MyClass { public string Name { get; set; } public string FaminlyName { get; set; } public int Phone { get; set; } public override bool Equals (object obj) { MyClass mobj = obj as MyClass; return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone); } public override int GetHashCode () { int hc = 0x00; hc ^= (this.Name != null) ? this.Name.GetHashCode() : 0; hc ^= (this.FaminlyName != null) ? this.FaminlyName.GetHashCode() : 0; hc ^= this.Phone.GetHashCode(); return hc; } }