Compare two vars of T in a generic method <T, U> (code port from C ++ to C #)
How to compare two vars of type T in a method of the general class <T, U>? Here is a sample code that causes the following compiler error:
Error CS0019 The operator '> =' cannot be applied to operands of type 'T' and 'T'
class IntervalSet< T, U >
{
public void Add ( T start, T end, ref U val )
{
// new interval is empty?
if (start >= end) // ERROR
return;
}
}
I am trying to transfer the source code from C ++ to C #, and C # is new to me. Thank you for your help.
+4
1 answer
You must specify C #, which is Tcomparable, otherwise you can only do System.Objectthings with T(and this is not so much), excluding creating a new instance, since C # does not even know it Thas a default constructor:
class IntervalSet< T, U >
where T : IComparable<T>
{
public void Add ( T start, T end, ref U val )
{
if (start.CompareTo(end) >= 0) {
}
}
}
, , int, string, DateTime .., .
: IComparable <T> ,
( #)
+7