4

我有一个函数,除其他外,它接受一个对象和一个类型,并将对象转换为该类型。然而,输入对象通常是一个双精度类型,并且类型有一些 int 变体(uint、long 等)。如果将整数作为双精度(如 4.0)传入,我希望它能够工作,但如果传入小数(4.3)则抛出异常。有没有更优雅的方法来检查 Type 是否是某种 int?

if (inObject is double && (targetType == typeof (int)
                         || targetType == typeof (uint)
                         || targetType == typeof (long)
                         || targetType == typeof (ulong)
                         || targetType == typeof (short)
                         || targetType == typeof (ushort)))
{
    double input = (double) inObject;
    if (Math.Truncate(input) != input)
        throw new ArgumentException("Input was not an integer.");
}

谢谢。

4

3 回答 3

6

这似乎可以满足您的要求。我只测试了双精度、浮点数和整数。

    public int GetInt(IConvertible x)
    {
        int y = Convert.ToInt32(x);
        if (Convert.ToDouble(x) != Convert.ToDouble(y))
            throw new ArgumentException("Input was not an integer");
        return y;
    }
于 2008-11-26T17:07:15.813 回答
2
int intvalue;
if(!Int32.TryParse(inObject.ToString(), out intvalue))
   throw InvalidArgumentException("Not rounded number or invalid int...etc");

return intvalue; //this now contains your value as an integer!
于 2008-11-26T19:46:28.987 回答
0

您应该能够使用 Convert.ToDecimal 和 x % y 的组合,我想,其中 y = 1 并检查结果 ==0;

于 2008-11-26T17:29:21.870 回答