我有一个这样的课:

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

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

谢谢。

允许使用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)

最佳答案

试试这个。

    public class Foo<T> : IEquatable<Foo<T>> where T : struct
    {
        List<T> lst;

        #region IEquatable<T> Members

        public bool Equals(Foo<T> other)
        {
            if (lst.Count != other.lst.Count)
            {
                return false;
            }

            for (int i = 0; i < lst.Count; i++)
            {
                if (!lst[i].Equals(other.lst[i]))
                {
                    return false;
                }
            }
            return true;
        }

        #endregion

        public override bool Equals(object obj)
        {
            var other = obj as Foo<T>;
            return other != null && Equals(other);
        }


    }

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

10-09 03:11