I는 다음과 같은 코드가 -는 가변 int로에만 할당 될 수있는 오류를 생성
using System;
namespace MyApp {
class Program {
static void Main() {
byte x = 10, y = 20;
Console.WriteLine(x.GetType());
Console.WriteLine(y.GetType());
//byte z = (x+y); Error: (9,14): error CS0266:
//Cannot implicitly convert type 'int' to 'byte'.
//An explicit conversion exists (are you missing a cast?)
byte z = (byte)(x+y);
Console.WriteLine(z.GetType());
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}
}
출력 :
System.Byte
System.Byte
System.Byte
10
20
30
하지만 byte z = x+y
을 사용하는 경우 명시 적 유형 캐스팅 대신 오류가 발생합니다. -
(9,14): error CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
그러나 코드에 표시된대로 컴파일러는 x
및 y
을 바이트로 읽습니다.
왜 2 바이트를 추가하면 명시 적 유형 캐스팅이 필요한 int가 생성되는 이유는 무엇입니까?
'x + y'는 실제로 'int'이기 때문에. [byte + byte = int ... why?] (https://stackoverflow.com/q/941584/3744182)와 [C#에서 바이트 빼기에 필요한 캐스트가 왜 나오는가?] (https://stackoverflow.com/q)를 참조하십시오./927391/3744182). – dbc