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

标签 c# reflection casting types

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

谢谢。

最佳答案

这似乎可以满足您的要求。我只测试了 double 、 float 和整数。

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

关于c# - 检查 C# 中的任何 int 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/321139/

相关文章:

c# - 获取插入行的ID cassandra .Net

java - Method.isBridge 用于什么?

java - sun.reflect 的来源在哪里?

javascript - 如何使用 && 正确检查两个条件

java - 通过反射创建时将对象转换为接口(interface)

c# - 运行代码片段并呈现结果的基本 VS 扩展(类似于 watch )

c# - 如何访问页面框架以通过 UWP 中的 UserControl 对象导航页面?

c# - 如何在父窗口最小化时防止子窗口最小化

go - 如何检查接口(interface)是 golang 中的 map[string]string

Java - 泛型 - 类 "Class<?>"的显式转换和转换方法