下面的程序将无法编译:为什么const int会隐式转换为一个字节,但是变量int不会呢?
class Program
{
static void Main(string[] args)
{
int x = 50;
Byte[] y = new Byte[3] { x, x, x };
}
}
不出意外,我会得到错误Cannot implicitly convert type 'int' to 'byte'
但是,如果我做x
一个常量,那么它会编译:
class Program
{
public const int x = 50;
static void Main(string[] args)
{
Byte[] y = new Byte[3] { x, x, x };
}
}
我很好奇这里发生了什么。如果int
无法隐式转换为字节,编译器是否会即时创建我的常量的“字节”版本,还是编译它,就像我已经进行了明确的转换,因为它认为常量值“安全“一个字节?也许,编译器将其解释为,如果我写了:
Byte[] y = new Byte[3] { 50, 50, 50 };
这让自认为这是合法的,我以什么编译器在这里做更多的好奇。
'const'值被替换。 – 2012-01-29 01:20:03
尝试与'公共const int x = 350;' – 2012-01-29 01:29:02
相关:http://stackoverflow.com/questions/9008637/why-does-this-implicit-conversion-from-int-to-uint-work – CodesInChaos 2012-01-29 16:53:59