问题描述
我有一个代码:
static short Sum(short a, short b)
{
return a + b;
}
而且它不能编译,saynig 不能将 'int' 转换为 'short'.我今天可能真的很累,但我看不到问题!
And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
推荐答案
而且它不能编译,saynig 不能将 'int' 转换为 'short'.我今天可能真的很累,但我看不到问题!
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)
根据需要提升操作数.
现在至于 原因 为何如此定义 - 老实说,我不知道.我不赞成因为它可能溢出"的论点——这表明应该将 byte + byte
定义为返回 short
,并且 int +int
应该返回 long
,两者都不为真.
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 return short
, and that int + int
should return long
, neither of which is true.
我在某处听说这可能与性能有关,但我不想肯定地说.(也许处理器通常只提供对 32 位和 64 位整数的整数运算?)
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# 不允许我将两个短裤相加为一个短裤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!