为什么我可以通过1为短,但不是int变量i? [英] Why can I pass 1 as a short, but not the int variable i?
问题描述
为什么第一和第二写入工作,但不是最后一次?有没有一种方法,我可以让他们的所有3个,并检测它是否为1,(INT)1或我通过?而真正为什么允许一个,但最后?第二个被允许,但不是最后真正吹拂我的心灵。
使用系统;
类节目
{
公共静态无效的写(简称V){}
静态无效的主要(字串[] args)
{
写(1); // OK
写((INT)1); // OK
INT I = 1;
写(我); //错误!?
}
}
前两个是不变的前pressions,最后一个没有了。
C#的规范允许从int短常量,而不是其他前pressions的隐式转换。这是一个合理的规则,因为常量编译器可以确保值适合目标类型,但它不能正常前pressions。
本规则与方针的隐式转换应该是无损线。
6.1.8隐定前pression转换
这是隐含的不断前pression转换允许下列转换:
- A 恒前pression 的(§7.18)类型的
INT
可转换为类型为sbyte
,字节
,短
,USHORT
,UINT
或ULONG
,提供的恒前pression值的是目标类型的范围之内。
- A 恒前pression 的类型
长
可转换为类型ULONG
,提供的恒前pression值的不是消极的。
块引用>(从C#语言规范版本3.0报价)
Why does the first and second Write work but not the last? Is there a way I can allow all 3 of them and detect if it was 1, (int)1 or i passed in? And really why is one allowed but the last? The second being allowed but not the last really blows my mind.
using System; class Program { public static void Write(short v) { } static void Main(string[] args) { Write(1);//ok Write((int)1);//ok int i=1; Write(i);//error!? } }
解决方案The first two are constant expressions, the last one isn't.
The C# specification allows an implicit conversion from int to short for constants, but not for other expressions. This is a reasonable rule, since for constants the compiler can ensure that the value fits into the target type, but it can't for normal expressions.
This rule is in line with the guideline that implicit conversions should be lossless.
6.1.8 Implicit constant expression conversions
An implicit constant expression conversion permits the following conversions:
- A constant-expression (§7.18) of type
int
can be converted to typesbyte
,byte
,short
,ushort
,uint
, orulong
, provided the value of the constant-expression is within the range of the destination type.- A constant-expression of type
long
can be converted to typeulong
, provided the value of the constant-expression is not negative.(Quoted from C# Language Specification Version 3.0)
这篇关于为什么我可以通过1为短,但不是int变量i?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!