C#不会让我来总结2短裤短 [英] C# does not let me sum two shorts to a short
问题描述
我有一个code:
静态短总和(短,短B)
{
返回A + B;
}
和它不编译,saynig不能转换'诠释'到'短'。我也许真的很累,但今天我看不到的问题!
和它不编译,saynig不能转换'诠释'到'短'。我也许真的很累,但今天我看不到的问题!
块引用>这只是语言的定义方式。整数类型+操作为定义的:
静态UINT OP +(UINT X,UINT Y)
静态INT运算+(INT X,int y)对
静态ULONG OP +(ULONG X,ULONG Y)
静态长运+(长×长Y)按要求操作数被提升。
现在作为的的原因的为什么它的定义方式 - 我不知道,说实话。我不买的,因为它可能溢出的说法 - 这将表明,
字节+字节
应该定义为返回短
,而INT + INT
应该返回长
,这两者都不是真实的。我在什么地方听说过,这可能是性能相关的,但我不希望肯定地说。 (也许处理器通常只在32位和64位整数提供整数运算?)
无论哪种方式,它并没有真正的无论的为什么是这种情况 - 这是语言的只是规则
请注意,混合式赋值操作符有一个隐式转换回相关类型,所以你的可以的写:
短X = 10;
短Y = 20;
X + = Y;I have a code:
static short Sum(short a, short b) { return a + b; }
And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
解决方案And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
It's just the way the language is defined. The + operator on integer types is defined for:
static uint op +(uint x, uint y) static int op +(int x, int y) static ulong op +(ulong x, ulong y) static long op +(long x, long y)
Operands are promoted as required.
Now as for the reasons why it's defined that way - I don't know, to be honest. I don't buy the argument of "because it could overflow" - that would suggest that
byte + byte
should be defined to returnshort
, and thatint + int
should returnlong
, neither of which is true.I've heard somewhere that it could be performance related, but I wouldn't like to say for sure. (Perhaps processors typically only provide integer operations on 32 and 64 bit integers?)
Either way, it doesn't really matter why it's the case - it's just the rules of the language.
Note that the compound assignment operators have an implicit conversion back to the relevant type, so you can write:
short x = 10; short y = 20; x += y;
这篇关于C#不会让我来总结2短裤短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!