C# 不允许我将两个短裤相加为一个短裤

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)