简体   繁体   English

C#:隐式将double转换为float?

[英]C#: implicitly convert double to float?

I know implicit conversions from double to float are not allowed by default in C#, but is there any way I can enable such conversions? 我知道在C#中默认不允许从double到float的隐式转换,但是有什么方法可以启用此类转换? With a pragma of some sort? 带有某种实用性吗? I'm not concerned with lack of precision (as my application doesn't require more than float precision anywhere), moreso just annoyed with having to always ensure I explicitly declare all decimal values as floats, or else I get compilation errors. 我不担心精度不足(因为我的应用程序在任何地方都不需要浮点数精度),而且总是不得不确保将所有十进制值明确声明为浮点数,否则我就烦恼了,否则我会遇到编译错误。

No you can't. 不,你不能。 Since such a conversion could result in a precision loss, and the compiler has no way of determining whether it will or will not, you have to explicitly say that you're aware of the cast. 由于这种转换可能会导致精度损失,并且编译器无法确定是否进行转换,因此您必须明确地说出您知道转换。

I'm unsure of what you mean by "explicitly declare decimals as floats", but in case you did not now, you can tell that a literal is a float by adding an f at the end 我不确定“将小数明确声明为浮点数”是什么意思,但是如果您现在不知道,则可以通过在末尾添加f来判断文字是浮点数

float a = 0.0;  // Wrong, implicit conversion.
float b = 0.0f; // OK. Can also be capital 'F'.

But if you're complaining about adding this one letter everywhere as a burden, then sorry, the answer is no, you can't work around that. 但是,如果您抱怨到处都增加一个字母,那很抱歉,答案是否定的,您不能解决这个问题。

No, there isn't any way to do it with implict conversion, but you may do it that way: 不,没有任何方式可以进行隐式转换,但是您可以这样做:

double a = 0.123456789123456789d;
float b = (float)a;
float c = Convert.ToSingle(a);
bool areBothSame = b == c;
Console.WriteLine("b == c: "areBothSame);
//Console Output:
//b == c: true

What Convert.ToSingle() does is that: Convert.ToSingle()的作用是:

public static float ToSingle(double value)
{
    return (float)value;
}

So doesn't really maters what you prefer, it does the same job. 因此,并没有真正满足您的喜好,而是完成了相同的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM