Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查C#中是否有任何int类型?_C#_Reflection_Casting_Types - Fatal编程技术网

检查C#中是否有任何int类型?

检查C#中是否有任何int类型?,c#,reflection,casting,types,C#,Reflection,Casting,Types,我有一个函数,除其他外,它接受一个对象和一个类型,并将该对象转换为该类型。然而,输入对象通常是一个double,并且类型是int的一些变体(uint、long等)。如果以双精度(如4.0)形式传入一个整数,我希望它可以工作,但如果传入一个十进制数(4.3),则抛出一个异常。有没有更优雅的方法来检查类型是否是某种int if (inObject is double && (targetType == typeof (int) ||

我有一个函数,除其他外,它接受一个对象和一个类型,并将该对象转换为该类型。然而,输入对象通常是一个double,并且类型是int的一些变体(uint、long等)。如果以双精度(如4.0)形式传入一个整数,我希望它可以工作,但如果传入一个十进制数(4.3),则抛出一个异常。有没有更优雅的方法来检查类型是否是某种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.");
}

谢谢。

这似乎满足了你的要求。我只测试了双打、浮点和整数

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

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

只是几句评论——1)别忘了浮动。2) 您可能需要使用Math.Round(),因为有时会由于浮点问题出现1.000000001而不是1.0。听起来您在复制系统中的功能。转换…好的点,Jon,我会确保记住浮点。Dave,当您将System.Convert.ChangeType从double改为int时,它会无声地进行取整。这段代码是为了在系统调用Convert之前防止这种情况发生。我想你会发现这不是真的?2.4 % 1 0.39999999999999991
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!