Вопрос по c#, .net – Почему результат вычитания параметра Int16 из переменной Int16 является Int32? [Дубликат]

10

Possible Duplicate:
byte + byte = int… why?

У меня есть такой метод:

 void Method(short parameter)
 {
     short localVariable = 0;
     var result = localVariable - parameter;
 }

Почему результатInt32 вместоInt16?

Error: User Rate Limit Exceededstackoverflow.com/questions/927391/… schnaader
Error: User Rate Limit Exceeded schnaader
Error: User Rate Limit Exceededstackoverflow.com/questions/941584Error: User Rate Limit Exceeded Jon Skeet
Error: User Rate Limit Exceeded Jader Dias
Error: User Rate Limit Exceeded Rhythmic Fistman

Ваш Ответ

5   ответов
11

Error: User Rate Limit Exceeded

short a = 2, b = 3;
short c = a + b;

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
1

Error: User Rate Limit Exceeded

short - short = int

Error: User Rate Limit Exceededdiscussed extensivelyError: User Rate Limit Exceeded[link] byte + byte = int… why?

Error: User Rate Limit Exceededgood informationError: User Rate Limit Exceededinteresting discussionsError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

I believe it's basically for the sake of performance. (In terms of "why it happens at all" it's because there aren't any operators defined by C# for arithmetic with byte, sbyte, short or ushort, just as others have said. This answer is about why those operators aren't defined.)

Processors have native operations to do arithmetic with 32 bits very quickly. Doing the conversion back from the result to a byte automatically could be done, but would result in performance penalties in the case where you don't actually want that behaviour.

-- Jon Skeets

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

7

short a = 2, b = 3;

short c = (short) (a + b);

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededstackoverflow.com/questions/941584/byte-byte-int-whyError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
3

(1)

(2)

(3)

short s = 0;

s++;                // <-- Ok
s += 1;             // <-- Ok
s = s + 1;          // <-- Compile time error!
s = s + s;          // <-- Compile time error!

byte b = 0;

b++;                // <-- Ok
b += 1;             // <-- Ok
b = b + 1;          // <-- Compile time error!
b = b + b;          // <-- Compile time error!

short s
s += (short)1;

1

Short result = Short.MaxValue + Short.MaxValue; 

Error: User Rate Limit Exceeded

Похожие вопросы