C# does not let me sum two shorts to a short(C# 不允许我将两个短裤相加为一个短裤)
问题描述
我有一个代码:
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# 不允许我将两个短裤相加为一个短裤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 不允许我将两个短裤相加为一个短裤


基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01