【问题标题】:Does a Type represent a numeric value C#类型是否表示数值 C#
【发布时间】:2009-09-22 09:59:37
【问题描述】:

我想知道是否有一个系统函数可以告诉我一个类型是否代表一个数值(对于自定义 TypeConverter)。当然检查每种已知类型都可以,但我不是很喜欢。

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

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

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

谢谢。

【问题讨论】:

标签: c# types


【解决方案1】:

如果您查看 Linq ExpressionNode(内部类)IsNumeric 方法,它基本上是针对每种类型进行测试。

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

这两个函数是针对原始类型进行测试的,比如

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 是一个特定于 Linq 的类,但您明白了:只需针对每种类型进行测试。

这是了解值是否为数字类型的最简单方法。

【讨论】:

  • 我认为这最终会归结为对类型的单独测试:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 2015-12-24
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
相关资源
最近更新 更多