1

Let me have a template class ( class Entry<T>), I want to make this class inherit from tow interfaces (IComparable<T> and IEquatable<T>), I've tried this:

class Entry<T> where T : IComparable<T>, IEquatable<T>
{
 /* Whatever in the class */
}

and I've tried the next code:

class Entry<T> : IEquatable<T>, where T : IComparable<T>
{
 /* Whatever in the class */
}

but non of them worked correctly, I don't know Why, anyone Can help me to know how I can use multiple interfaces inheritance?

4

1 回答 1

2

使用以下签名来实现 IEquatable<T>and IComparable<T>

public class Entry<T> : IComparable<T>, IEquatable<T>
{
    public int CompareTo(T other)
    {
        //compare logic... 
    }

    public bool Equals(T other)
    {
        return CompareTo(other) == 0;
    }
}

您的第一个示例是使用该where子句形成一个泛型类型约束,该约束表示“只接受实现 IComparable<T>IEquatable<T>的类型参数”。

你的第二个例子有无效的语法。看起来您是在说T IEquatable<T>必须实施IComparable<T>。如果你想这样做,那么你还必须Tclass Entry<T>.

于 2013-05-11T23:48:35.783 回答