【发布时间】:2012-01-29 01:18:25
【问题描述】:
以下程序将无法编译:
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 隐式转换为字节,编译器是否会即时创建我的 const 的“字节”版本,还是像我进行显式转换一样对其进行编译,因为它认为是常量值一个字节的“安全”?也许编译器会像我这样解释:
Byte[] y = new Byte[3] { 50, 50, 50 };
因为这是合法的,所以我更好奇编译器在这里做了什么。
【问题讨论】:
-
const值被替换。 -
试试
public const int x = 350;