为什么C#不需要显式转换来转换Long To Double?

tvo*_*olf 8 c# casting

起初,抱歉我的英语不好.我有代码片段:

long x = 9223372036854775807L;
double f = x;
Console.WriteLine(x);           
Console.WriteLine(f);
Run Code Online (Sandbox Code Playgroud)

输出是:

9223372036854775807
9,22337203685478E+18
Run Code Online (Sandbox Code Playgroud)

编译和执行此代码时,我没有收到任何错误.在将Long转换为Double时,我们的精度会下降.为什么C#在这种情况下不需要显式转换?

谢谢大家.

Joh*_*ner 12

该语言内置了一些隐式转换.

下表来自文档,这就是为什么允许您在没有显式强制转换或转换的情况下分配值的原因:

From        To
===============================================================================
sbyte       short , int, long, float, double, or decimal
byte        short , ushort, int, uint, long, ulong, float, double, or decimal
short       int , long, float, double, or decimal
ushort      int , uint, long, ulong, float, double, or decimal
int         long , float, double, or decimal
uint        long , ulong, float, double, or decimal
long        float , double, or decimal
char        ushort , int, uint, long, ulong, float, double, or decimal
float       double
ulong       float , double, or decimal
Run Code Online (Sandbox Code Playgroud)

在它所述的文件中(强调我的):

从int,uint,long或ulong到float以及从long或ulong到double的转换中,精度但不是大小可能会丢失.

  • 我不喜欢这个。强类型语言不应该在没有显式转换的情况下失去压力。 (2认同)