通过强制转换或Convert.ToSingle()将double转换为float? [英] Convert double to float by cast or Convert.ToSingle()?
本文介绍了通过强制转换或Convert.ToSingle()将double转换为float?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,我可以通过强制转换(float)
或 Convert.ToSingle()
将double转换为float.
In C# I can convert doubles to floats by a cast (float)
or by Convert.ToSingle()
.
double x = 3.141592653589793238463;
float a = (float)x;
float b = Convert.ToSingle(x);
a
和 b
相等.
两种技术之间是否有区别?我应该选择哪一个?为什么?
Are there any differences between both techniques? Which one should I prefer and why?
推荐答案
来自 .NET参考源:
public static float ToSingle(double value)
{
return (float)value;
}
因此,您的答案是,它们在引擎盖下完全相同.
So, your answer is that they are exactly the same, under the hood.
两者之间的任何偏爱严格来说都是个人风格的选择.就我个人而言,我总是会使用演员表,因为它较短,而且对我来说似乎更惯用.
Any preference between the two is strictly a personal style choice. Personally, I would always use the cast as it is shorter and and just seems more idiomatic to me.
这篇关于通过强制转换或Convert.ToSingle()将double转换为float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文