简体   繁体   中英

Does a Type represent a numeric value C#

I am wondering if there is a system function which will tell me if a type represents a numeric value (for a custom TypeConverter). Sure checking for each type known type works ok, but I don't really like it.

        if (destinationType == typeof( int))
            return true;

        if (destinationType == typeof( Int16))
            return true;

        if (destinationType == typeof( Int32))
            return true 
        ...
        if (destinationType == typeof( float))
            return true;
        ...

Thanks.

If you look at Linq ExpressionNode (internal class) IsNumeric method, it is basically testing against every type.

if (!IsFloat(type))
{
    return IsInteger(type);
}
return true;

And the two function are testing against the primitive type, like

internal static bool IsInteger(StorageType type)
{
    if ((((type != StorageType.Int16) && (type != StorageType.Int32)) && ((type != StorageType.Int64) && (type != StorageType.UInt16))) && (((type != StorageType.UInt32) && (type != StorageType.UInt64)) && (type != StorageType.SByte)))
    {
        return (type == StorageType.Byte);
    }
    return true;
}

StorageType is a Linq specific class, but you get the idea: just test against every type.

It is the easiest way to know if the value is a numeric type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM