本文介绍了从double转换为int的最佳(最安全)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对将双精度型转换为int的最佳方法感到好奇.在此,运行时安全是我的主要关注点(不一定是最快的方法,但这是我的次要关注点).我留下了一些我可以在下面提出的选择.任何人都可以权衡哪种最佳做法吗?没有列出的更好的方法来实现这一点?
I'm curious as to the best way to convert a double to an int. Runtime safety is my primary concern here (it doesn't necessarily have to be the fastest method, but that would be my secondary concern). I've left a few options I can come up with below. Can anyone weigh in on which is best practice? Any better ways to accomplish this that I haven't listed?
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; }
推荐答案
我认为您最好的选择是:
I think your best option would be to do:
checked
{
try
{
int bar = (int)foo;
}
catch (OverflowException)
{
...
}
}
来自显式数值转换表
注意:选项2 还会在出现OverflowException
时抛出OverflowException
必填.
Note: Option 2 also throws an OverflowException
when required.
这篇关于从double转换为int的最佳(最安全)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!