How to compare two vars of type T in a method of a generic class< T, U >? Here is an example code which throws the following compiler error:
Error CS0019 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 try to port source from C++ to C# and C# is new to me. Thanks for your help.
You must tell C# that T
is comparable, otherwise you can only do System.Object
things with T
(and that's not much), excluding creating a new instance, since C# does not even know whether T
has 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) {
}
}
}
Note that standard types like int
, string
, DateTime
etc. all implement this interface.
See: IComparable<T> Interface ,
Constraints on Type Parameters (C# Programming Guide)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.