Initializing C # Generators Using Type Values

In the following class:

public class Example<T> where T : IComparable {
    private T _min;
    private T _max;

    public Example() {
        // _min = T.MinValue;
        // _max = T.MaxValue;
    }

    public Example(T min, T max) {
        _min = min;
        _max = max;
    }

    public bool Contains(T val) {
        return (val.CompareTo(_min) < 0) && (val.CompareTo(_max) > 0);
    }
}

What would be the best way to initialize members for their minimum and maximum type values ​​in the default constructor? I know that this imposes one more restriction on the allowed types for the general type, but this is good for my purposes.

Also, if the type of supported infinite values ​​like float or double, is there a way to detect this and set the values ​​accordingly?

+3
source share
5 answers

There are no restrictions that would allow you to get MinValue and MaxValue. The only value you can get with a strong type is the default value (default (T)).

, MinValue MaxValue, Reflection, .

: _isMinSpecified _isMaxSpecified Contains - . , , true.

+9

, , , . (Int32, float ..) min max, - . , -, , :)

, , float double, ?

, " " , "", ( ).

0

. , , ... , MinValue MaxValue , .

0

# 3.5, :

public static class GenericLimit<T>
{
    public static readonly T MinValue = (T)MinValue.GetType ().GetField ("MinValue").GetValue (MinValue);
    public static readonly T MaxValue = (T)MaxValue.GetType ().GetField ("MaxValue").GetValue (MaxValue);
}

public class MinMax<T> where T : struct
{
    private readonly T minValue = GenericLimit<T>.MinValue;
    private readonly T maxValue = GenericLimit<T>.MaxValue;

    public T Min { get; private set; }
    public T Max { get; private set; }

    public static bool InRange (T value, T min, T max)
    {
        return (Operator.GreaterThanOrEqual (value, min) && Operator.LessThanOrEqual (value, max));
    }

    public MinMax () { Reset (); }

    public void Update (T n)
    {
        if (Operator.LessThan (n, Min)) Min = n;
        if (Operator.GreaterThan (n, Max)) Max = n;
    }

    public void Reset ()
    {
        Min = maxValue;
        Max = minValue;
    }
}

General math from C # in depth to (thanks to Jon Skeet and Marc Gravell).

PS Any suggestions on simplifying reflection are welcome.

0
source
public Example() {
    _min = default (T);
    _max = default (T);
}

Sorry, this is not what you are looking for.

-1
source

Source: https://habr.com/ru/post/1721253/


All Articles