检查C#中的任何int类型?

Eri*_*c W 4 c# reflection types casting

我有一个函数,除其他外,它接受一个对象和一个类型,并将该对象转换为该类型.但是,输入对象通常是double,并且类型有一些int(uint,long等)的变体.如果圆数作为double传递(如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.");
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Amy*_*y B 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;
    }
Run Code Online (Sandbox Code Playgroud)