【问题标题】:Check for any int type in C#?检查 C# 中的任何 int 类型?
【发布时间】:2010-09-24 04:23:37
【问题描述】:

我有一个函数,除其他外,它接受一个对象和一个类型,并将对象转换为该类型。然而,输入对象通常是一个双精度类型,并且类型有一些 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.");
}

谢谢。

【问题讨论】:

  • 只需几个 cmets - 1) 不要忘记花车。 2) 您可能想要使用 Math.Round(),因为有时会出现 1.000000001 而不是 1.0 由于浮点问题。
  • 听起来你在 System.Convert 中复制功能...
  • 好点,乔恩,我会确保记住花车。戴夫,当您将 System.Convert.ChangeType 从 double 转换为 int 时,它会默默地进行银行家四舍五入。此代码是为了防止在 System.Convert 调用之前发生这种情况。

标签: c# reflection casting types


【解决方案1】:

这似乎符合您的要求。我只测试了双精度、浮点数和整数。

    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;
    }

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我想你会发现那不是真的... ?2.4 % 1 0.39999999999999991
    【解决方案3】:
    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!
    

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2013-04-29
      • 2012-11-28
      • 1970-01-01
      相关资源
      最近更新 更多