Frage

I'm mucking about, making a generic class, and all this time I thought using types that implemented IComparable enabled using the comparison operators.

I know .CompareTo() can perform functionally the same operations, but I have a nagging feeling that there must be an interface that implements the comparison operators.

War es hilfreich?

Lösung 2

No. Operators cannot be specified via an interface.

Interfaces define the properties, methods, and events [but not operators] that classes can implement.

The closest interface, as noted, is IComparable.

Some languages have more sugar mapping (e.g Scala) but not VB.NET or C#.

Andere Tipps

Rather than by implementing an interface, this is accomplished through operator overloading. So, to overload the greater-than and less-than comparison operators, for instance, you could do something like this:

Public Class MyNumber
    Public Value As Integer

    Public Overloads Shared Operator >(ByVal x As MyNumber, ByVal y As MyNumber) As Boolean
        Return (x.Value > y.Value)
    End Operator

    Public Overloads Shared Operator <(ByVal x As MyNumber, ByVal y As MyNumber) As Boolean
        Return (x.Value < y.Value)
    End Operator
End Class

Since operator overloads are defined as Shared, they cannot be declared by an interface. Interfaces in VB.NET can only declare instance-members. They cannot declare shared members.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top