C# - how to determine whether a Type is a number

后端 未结 18 2272
傲寒
傲寒 2020-11-28 22:47

Is there a way to determine whether or not a given .Net Type is a number? For example: System.UInt32/UInt16/Double are all numbers. I want to avoid a long switc

18条回答
  •  Happy的楠姐
    2020-11-28 23:27

    oops! Misread the question! Personally, would roll with Skeet's.


    hrm, sounds like you want to DoSomething on Type of your data. What you could do is the following

    public class MyClass
    {
        private readonly Dictionary> _map = 
            new Dictionary> ();
    
        public MyClass ()
        {
            _map.Add (typeof (int), o => return SomeTypeSafeMethod ((int)(o)));
        }
    
        public SomeResult DoSomething(T numericValue)
        {
            Type valueType = typeof (T);
            if (!_map.Contains (valueType))
            {
                throw new NotSupportedException (
                    string.Format (
                    "Does not support Type [{0}].", valueType.Name));
            }
            SomeResult result = _map[valueType] (numericValue);
            return result;
        }
    }
    

提交回复
热议问题