我一直在研究IEqualityComparer和IEquitable。
从?这样的帖子来看,两者之间的区别现在已经很明显了。"IEqualityComparer是对T类型的两个对象执行比较的对象的接口。“
遵循https://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx的示例,IEqualityComparer的目的是明确和简单的。
我在https://dotnetcodr.com/2015/05/05/implementing-the-iequatable-of-t-interface-for-object-equality-with-c-net/上学习了如何使用它的示例,并得到了以下代码:
class clsIEquitable
{
public static void mainLaunch()
{
Person personOne = new Person() { Age = 6, Name = "Eva", Id = 1 };
Person personTwo = new Person() { Age = 7, Name = "Eva", Id = 1 };
//If Person didn't inherit from IEquatable, equals would point to different points in memory.
//This means this would be false as both objects are stored in different locations
//By using IEquatable on class it compares the objects directly
bool p = personOne.Equals(personTwo);
bool o = personOne.Id == personTwo.Id;
//Here is trying to compare and Object type with Person type and would return false.
//To ensure this works we added an overrides on the object equals method and it now works
object personThree = new Person() { Age = 7, Name = "Eva", Id = 1 };
bool p2 = personOne.Equals(personThree);
Console.WriteLine("Equatable Check", p.ToString());
}
}
public class Person : IEquatable<Person>
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Equals(Person other)
{
if (other == null) return false;
return Id == other.Id;
}
//These are to support creating an object and comparing it to person rather than comparing person to person
public override bool Equals(object obj)
{
if (obj is Person)
{
Person p = (Person)obj;
return Equals(p);
}
return false;
}
public override int GetHashCode()
{
return Id;
}
}我的问题是我为什么要用它?下面的简单版本(bool O)似乎需要大量额外的代码:
//By using IEquatable on class it compares the objects directly
bool p = personOne.Equals(personTwo);
bool o = personOne.Id == personTwo.Id;发布于 2016-06-09 21:00:46
泛型集合使用IEquatable<T>来确定相等性。
来自msdn的文章https://msdn.microsoft.com/en-us/library/ms131187.aspx
在测试包含、IEquatable、LastIndexOf和Remove等方法中是否相等时,通用集合对象(如Dictionary、List和LinkedList )使用该IndexOf接口。它应该为可能存储在泛型集合中的任何对象实现。
这在使用结构时提供了额外的好处,因为调用IEquatable<T>等于方法并不像调用基本object等于方法那样将结构框化。
https://stackoverflow.com/questions/37731419
复制相似问题