在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
鉴于以下课程
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经覆盖了该Equals方法,因为它Foo代表了Foos表的一行.哪个是覆盖的首选方法GetHashCode?
覆盖为什么重要GetHashCode?
我有2个List<Animal>我想比较并找到2个List<Animal>对象之间的区别.
Animal object包含以下属性.
ID
名称
年龄
List中list1有10个Animal对象,其中list2有10个Animal对象.在这2个列表中有2个项目(Animal对象相同)
当我使用该Except函数时,我希望remainingList它只包含2列表中不常见的对象.但是,remainingList包含一个副本list1.
我怎么解决这个问题?
List<Animal> remainingList = list1.Except(list2).toListAsync();
Run Code Online (Sandbox Code Playgroud)