文字和隐式收缩转换 [英] Literals and implicit narrowing conversions

查看:158
本文介绍了文字和隐式收缩转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一)不应该被分配如下导致错误,因为数100是文字型的 INT 的并且由于编译器不允许隐式收缩转换?

a) Shouldn’t the following assignment cause an error, since number 100 is a literal of type int and since compiler doesn’t allow implicit narrowing conversions?

byte b = 100; 



b)若编译器不抱怨从 INT文字的到的字节类型的,那么为什么不也允许隐式收缩转换隐式收缩转换双击文字的到的 float类型的(我知道我们能够避免这个错误通过指定浮动文字使用F / F后缀)?

b) If compiler doesn’t complain about implicit narrowing conversion from int literal to type byte, then why doesn’t it also allow an implicit narrowing conversion from double literal to type float ( I realize we could avoid this error by specifying float literal using F/f suffix )?

byte b=16; //OK
float f1=16.9; //error



谢谢

推荐答案

这是覆盖在C#语言规范第6.1.8。它是合法的恒定前$ P $ int类型pssions要转换到sbyte,字节,短,USHORT,UINT或ULONG提供的值是目标类型的范围内。它是相当容易的C#编译,以确定该值是否在适当范围内,从而使转化率。

This is covered in section 6.1.8 of the C# language spec. It is legal for constant expressions of type int to be converted to sbyte, byte, short, ushort, uint or ulong provided the value is within the range of the target type. It is fairly easy for the C# compiler to determine if the value is within the appropriate range and hence allow the conversion.

对于双的情况下,C#朗规范没有特别要求,为什么这是不允许的。我的猜测是它必须做有困难的决定,如果双值浮点值的范围内适合。获取浮点precision正确的是一个非常困难的任务,大概这么多所以并不认为是值得的成本(如果有可能的话)

As for the double case, the C# lang spec does not specifically call out why this is not allowed. My guess is it has to do with difficulties in determining if the double value can fit within the float value. Getting floating point precision correct is a very difficult task and probably so much so it wasn't deemed to be worth the cost (if it was possible at all)

这篇关于文字和隐式收缩转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆