gpt4 book ai didi

C# 实现 IEquatable.Equal

转载 作者:太空狗 更新时间:2023-10-29 22:15:14 24 4
gpt4 key购买 nike

我有这样一个类:

public class Foo<T> : IEquatable<T> where T : struct
{
List<T> lst;
[Other irrelevant member stuff]
}

我想实现 IEquatable<T> Foo 类的接口(interface)。我需要做什么。为简单起见,我只想检查列表成员是否相等。

谢谢。

C# 4.0 支持的答案是允许的。

更新:这是我目前拥有的:

public bool Equals(Foo<T> foo)
{
return lst.Equals(foo.lst);
}

public override bool Equals(Object obj)
{
if (obj == null) return base.Equals(obj);

if (!(obj is Foo<T>))
{
throw new Exception("The 'obj' argument is not a Foo<T> object.");
}
else
{
return Equals(obj as Foo<T>)
}
}

public override int GetHashCode()
{
return this.lst.GetHashCode();
}

public static bool operator ==(Foo<T> f1, Foo<T> f2)
{
return f1.Equals(f2);
}

public static bool operator !=(Foo<T> f1, Foo<T> f2)
{
return (!f1.Equals(f2));
}

我收到这个错误:

Error 1 'Foo<T>' does not implement interface member 'System.IEquatable<T>.Equals(T)

最佳答案

不幸的是,List<T>不会覆盖 EqualsGetHashCode .这意味着即使您已经更正了类声明,您仍需要自己执行比较:

public bool Equals(Foo<T> foo)
{
// These need to be calls to ReferenceEquals if you are overloading ==
if (foo == null)
{
return false;
}
if (foo == this)
{
return true;
}
// I'll assume the lists can never be null
if (lst.Count != foo.lst.Count)
{
return false;
}
for (int i = 0; i < lst.Count; i++)
{
if (!lst[i].Equals(foo.lst[i]))
{
return false;
}
}
return true;
}

public override int GetHashCode()
{
int hash = 17;
foreach (T item in lst)
{
hash = hash * 31 + item.GetHashCode();
}
return hash;
}

public override bool Equals(Object obj)
{
// Note that Equals *shouldn't* throw an exception when compared
// with an object of the wrong type
return Equals(obj as Foo<T>);
}

在重载 == 和 != 之前,我个人会非常仔细地考虑。如果您确实决定实现它们,您应该考虑其中一个或两个值都为 null 的情况:

public static bool operator ==(Foo<T> f1, Foo<T> f2)
{
if (object.ReferenceEquals(f1, f2))
{
return true;
}
if (object.ReferenceEquals(f1, null)) // f2=null is covered by Equals
{
return false;
}
return f1.Equals(f2);
}

关于C# 实现 IEquatable<T>.Equal<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2080394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com