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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/321139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:08:09  来源:igfitidea点击:

Check for any int type in C#?

c#reflectioncastingtypes

提问by Eric W

I have a function that, among other things, takes in an object and a Type, and converts the object into that Type. However, the input object is often a double, and the type some variation of int (uint, long, etc.). I want this to work if a round number is passed in as a double (like 4.0), but to throw an exception if a decimal is passed in (4.3). Is there any more elegant way to check if the Type is some sort of int?

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

Thanks.

谢谢。

采纳答案by Amy B

This seems to do what you ask. I have only tested it for doubles, floats and ints.

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

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

回答by PolyglotProgrammer

You should be able to use a combination of Convert.ToDecimal and x % y, I would have thought, where y = 1 and checking the result ==0;

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

回答by Ricardo Villamil

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!