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

后端 未结 18 2310
傲寒
傲寒 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条回答
  •  忘掉有多难
    2020-11-28 23:26

    Modified skeet's and arviman's solution utilizing Generics, Reflection, and C# v6.0.

    private static readonly HashSet m_numTypes = new HashSet
    {
        typeof(int),  typeof(double),  typeof(decimal),
        typeof(long), typeof(short),   typeof(sbyte),
        typeof(byte), typeof(ulong),   typeof(ushort),
        typeof(uint), typeof(float),   typeof(BigInteger)
    };
    

    Followed By:

    public static bool IsNumeric( this T myType )
    {
        var IsNumeric = false;
    
        if( myType != null )
        {
            IsNumeric = m_numTypes.Contains( myType.GetType() );
        }
    
        return IsNumeric;
    }
    

    Usage for (T item):

    if ( item.IsNumeric() ) {}
    

    null returns false.

提交回复
热议问题