我很好奇将 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/