C# Generics : how to use x.MaxValue / x.MinValue (int, float, double) in a generic class

前端 未结 4 1881
天涯浪人
天涯浪人 2021-01-05 03:59

I\'m using the WPF Extended Toolkit ( http://wpftoolkit.codeplex.com/ ).

It has a nice NumericUpDown control that I\'d like to use, but internally it uses doubles -

4条回答
  •  长情又很酷
    2021-01-05 04:35

    As this is also useful in Testing scenarios:

    You may use extension methods, such that in C#6 (introducing nameof) you could write:

    public static class TypeExtension
    {
        public static T MinValue(this Type self)
        {
            return (T)self.GetField(nameof(MinValue)).GetRawConstantValue();
        }
    
        public static T MaxValue(this Type self)
        {
            return (T)self.GetField(nameof(MaxValue)).GetRawConstantValue();
        }
    
    }
    

    and invoke through some admittedly ugly syntax:

    var intMinValue = typeof(int).MinValue();
    

    which in your generic method would be

    var typeMinValue = typeof(T).MinValue();
    

    Note, that I am not certain that all primitive types declare their Min/Max values as constants. Use GetValue instead.

提交回复
热议问题