[英]Why should we use literals in C#?
在一些C#代码中我看过这样的staments:
float someFloat = 57f;
我想知道为什么我们应该在上面的例子中使用像f
这样的文字?
主要是因此编译器确切地知道我们的意思 - 特别是对于重载分辨率:
Foo(57f);
应该调用Foo(int)
/ Foo(float)
/ Foo(decimal)
吗?
实际上,我不喜欢记住事物 - 另一种选择是:
float someFloat = (float)57;
这不是运行时强制转换 - 它与57f
相同(在IL级别)。 它唯一不同的是带有额外精度的decimal
:
decimal someDecimal = (decimal)57.0; // same as 57M, not 57.0M (scale is different)
上面的“f”是类型后缀。 这告诉编译器提供的文字的确切类型。 这是使用的,因此编译器可以为文字分配适当的存储量(精度)。 默认情况下,浮点文字的存储空间为“double”。 如果添加“f”作为后缀,则文字只会获得浮点数的存储空间,而精度较低。
double d = 50.1234; // given double storage
double d = 50.1234f; // given float storage, which might lose precision compared to double
默认情况下,赋值运算符右侧的实数数字文字被视为double。 因此,要初始化float变量,请使用后缀f或F,例如:
float x = 3.5F;
如果您不在前一个声明中使用后缀,则会出现编译错误,因为您试图将double值存储到float变量中。
为什么我们应该使用文字?
int / int = int
但 int / float = float
:
int timespanInMS = 500;
Console.WriteLine("Execution time: {0} sec.", timespanInMS / 1000);
Console.WriteLine("Execution time: {0} sec.", timespanInMS / 1000F);
// Result:
// Execution time: 0 sec.
// Execution time: 0.5 sec.
看看这篇文章解释了很多关于C#中的数字文字: http : //www.blackwasp.co.uk/CSharpNumericLiterals.aspx
以下是文章的一些摘录:
float unitPrice = 123.45; //这不会编译
这里的问题是你不能总是隐式地将double(123.45)转换为float。 C#编译器理解这一点并停止编译代码
因为57是整数,57.0是双精度。 你试图得到一个浮点数,这是一个单精度数。 这就引出了一个问题,你为什么要使用一个精密浮子呢?
有关C#文字的更多信息,请参阅http://www.blackwasp.co.uk/CSharpNumericLiterals.aspx 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.