c# - 从 double 转换为 int 的最佳(最安全)方法

标签 c# type-conversion explicit tryparse

我很好奇将 double 转换为整数的最佳方法。运行时安全是我在这里的主要关注点(它不一定是最快的方法,但这是我的次要关注点)。我在下面留下了一些我可以想出的选项。任何人都可以权衡哪种是最佳实践吗?有没有我没有列出的更好的方法来完成这个?

        double foo = 1;
        int bar;

        // Option 1
        bool parsed = Int32.TryParse(foo.ToString(), out bar);
        if (parsed)
        {
            //...
        }

        // Option 2
        bar = Convert.ToInt32(foo);

        // Option 3
        if (foo < Int32.MaxValue && foo > Int32.MinValue) { bar = (Int32)foo; }

最佳答案

我认为您最好的选择是:

checked
{
    try
    {
        int bar = (int)foo;
    }
    catch (OverflowException)
    {
     ...          
    }
}

来自 Explicit Numeric Conversions Table

When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

备注:Option 2还会在需要时抛出 OverflowException

关于c# - 从 double 转换为 int 的最佳(最安全)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3549179/

相关文章:

c# - 使用现有数据库时 Entity Framework 代码优先的好处

c# - SSIS脚本组件转换C#代码日期转换

c# - c#中long到decimal的转换

python - 将16位的最高字节转换为python中的signed int

c++ - 为什么某些隐式类型转换在一台机器上是安全的而不是在另一台机器上?我怎样才能防止这个跨平台问题?

entity-framework-4 - Entity Framework 显式加载示例

c# - ASP.NET MVC - 如何实现带有必填字段的可选嵌套模型?

c# - 为什么我在 Visual Studio 编辑器中得到 'Localizable string'?

c# - 为什么 Azure Function 应用程序中使用的 Microsoft.Azure.WebJobs.HttpTriggerAttribute 是参数属性而不是方法属性?

<label> 里面的 Django &lt;input&gt;