为什么一个const int的隐式转换为字节,但是一个变量int不? [英] Why does a const int implicitly cast to a byte, but a variable int does not?

查看:159
本文介绍了为什么一个const int的隐式转换为字节,但是一个变量int不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序将不能编译:

The following program will not compile:

   class Program
   {
      static void Main(string[] args)
      {
         int x = 50;
         Byte[] y = new Byte[3] { x, x, x };
      }
   }

不出意外,我会得到错误无法隐式转换类型'诠释'到'字节'

但是,如果我做 X 一个常量,那么它会编译:

However, if I make x a const, then it will compile:

   class Program
   {
      public const int x = 50;

      static void Main(string[] args)
      {
         Byte[] y = new Byte[3] { x, x, x };
      }
   }

我很好奇,什么是怎么回事。如果 INT 不能隐式转换为字节,该编译器动态创建一个字节版本,我的常量,或者它编译它,就好像我已经把在显式转换,因为它认为恒定值安全为一个字节?也许是编译器间$ P $点这个,就好像我写的:

I'm curious as to what's going on here. If an int cannot be implicitly cast to a byte, does the compiler create a "byte" version of my const on the fly, or does it compile it as if I had put in an explicit cast, as it deems the constant value "safe" for a byte? Perhaps the compiler interprets this as if I had written:

Byte[] y = new Byte[3] { 50, 50, 50 };

这让自认为这是合法的,我以什么编译器在这里做更多的好奇。

It makes since that this is legal, I'm more curious as to what the compiler is doing here.

推荐答案

编译器将只把常量,如果你写的号码存在,但需要有一个隐含的转换。

The compiler will just treat the constant as if you wrote the number there, but there needs to be an implicit conversion.

在你的第三个片段中,这三个 50 都是 System.Int32的。将鼠标悬停在它和读取Visual Studio中的提示。为什么这里没有编译器错误?因为编译器知道在编译时的价值,并知道它装进一个字节

In your third snippet, those three 50 are all System.Int32. Hover your mouse over it and read the tooltip in Visual Studio. Why doesn't the compiler error here? Because the compiler knows the value at compile time and knows it will fit inside a byte.

这篇关于为什么一个const int的隐式转换为字节,但是一个变量int不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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