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

前端 未结 4 1771
天涯浪人
天涯浪人 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:32

    Well, given that you can get at the type at execution time, you could rely on the fact that all of the numeric types in .NET have MinValue and MaxValue fields, and read them with reflection. It wouldn't be terribly nice, but easy enough to do:

    using System;
    using System.Reflection;
    
    // Use constraints which at least make it *slightly* hard to use
    // with the wrong types...
    public class NumericUpDown where T : struct,
        IComparable, IEquatable, IConvertible
    {
        public static readonly T MaxValue = ReadStaticField("MaxValue");
        public static readonly T MinValue = ReadStaticField("MinValue");
    
        private static T ReadStaticField(string name)
        {
            FieldInfo field = typeof(T).GetField(name,
                BindingFlags.Public | BindingFlags.Static);
            if (field == null)
            {
                // There's no TypeArgumentException, unfortunately. You might want
                // to create one :)
                throw new InvalidOperationException
                    ("Invalid type argument for NumericUpDown: " +
                     typeof(T).Name);
            }
            return (T) field.GetValue(null);
        }
    }
    
    class Test
    {
        static void Main()
        {
            Console.WriteLine(NumericUpDown.MaxValue); 
            Console.WriteLine(NumericUpDown.MinValue);
        }
    }
    

    Note that if you use this with an inappropriate type, I've tried to force a compile-time error as best I can... but it won't be foolproof. If you manage to find a structure with all the right interfaces but without MinValue and MaxValue fields, then any attempt to use the NumericUpDown with that type will cause an exception to be thrown.

提交回复
热议问题