The need to realize an overall result less and more than an operation

I CAN'T hardcode the data type. I need strict data entry. I need to use TValue a <= TValue b. Again, there is an Absolutely NO way to do something like (double) a. This is part of the essential implementation of the library. The only thing that is common to common values ​​is that they have static types. Not compatible and other interfaces do not seem to work.

+3
source share
3 answers

Why is IComparable not working for you?

You cannot get syntactic sugar using "<" and ">", but you can check if the CompareTo result is less than or greater than 0, which gives you the same information.

, .

static void Main(string[] args)
{
    Console.WriteLine(1.IsGreaterThan(2));
    Console.WriteLine(1.IsLessThan(2));
}

public static bool IsGreaterThan<T>(this T value, T other) where T : IComparable
{
    return value.CompareTo(other) > 0;
}

public static bool IsLessThan<T>(this T value, T other) where T : IComparable
{
    return value.CompareTo(other) < 0;
}
+31

System.Collections.Generic.Comparer<T>.Default.Compare(x,y) - , 0 .

IComparable<T>, IComparable, , Nullable<T> -of-structs.

+15

?

, - ; , - GetHashCode() ToString(), .

, :

If you used IComparableeither IComparable<T>for your type, you can use Comparer<T>.Defaultto get the last option automatically, which makes consumer comparisons a little shorter to write, and is an alternative to the general restriction requiring the type to be IComparable<T>.

+3
source

All Articles