簡體   English   中英

如果 byte + byte = int 為什么 int + int 不短/長? 在 C#

[英]if byte + byte = int why int + int is not short/long? in C#

byte num1 = 5;
byte num2 = 6;

byte res = num1 + num2; 
//Adding bytes asks for a explicit cast to int - "Cannot Implicitly Convert 'int' to 'byte'

這可以通過假設算術運算導致溢出的情況來證明。 因此,如果這是這種情況,那么 int 呢?

int num1 = 2;
int num2 = 4;

int res = num1 + num2;
// This works, but when we take the previous assumption to consideration here
// here int may also lead to overflow right 

所以這也應該拋出一個演員錯誤,它應該要求很長時間並且鏈條繼續對嗎?

已經有另一個與此類似的 stackoverflow 問題,但它沒有回答這個問題。 byte + byte = int ... 為什么?

僅僅因為它“可以被證明是合理的”,並不意味着這就是原因。

埃里克·利珀特(Eric Lippert),誰會知道,在評論你鏈接的問題時很清楚這一點:

下面的各種思考是對設計考慮的合理近似。 更籠統地說:我不認為字節是“數字”; 我認為它們是可以解釋為數字、字符或 colors 或其他任何東西的位模式。 如果您要對它們進行數學運算並將它們視為數字,那么將結果移動到通常被解釋為數字的數據類型是有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM