相关疑难解决方法(0)

为什么ushort + ushort等于int?

以前我今天尝试添加两个ushorts,我注意到我必须将结果反馈给ushort.我认为它可能会成为一个uint(以防止可能的意外溢出?),但令我惊讶的是它是一个int(System.Int32).

是否有一些聪明的理由或者是因为i​​nt被视为'基本'整数类型?

例:

ushort a = 1;
ushort b = 2;

ushort c = a + b; // <- "Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)"
uint d = a + b; // <- "Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)"

int e = a + b; // <- Works!
Run Code Online (Sandbox Code Playgroud)

编辑:就像GregS的回答所说,C#规范说两个操作数(在这个例子中是'a'和'b')应该转换为int.我对为什么这是规范的一部分的根本原因感兴趣:为什么C#规范不允许直接对ushort值进行操作?

c# types integer-arithmetic

28
推荐指数
3
解决办法
1万
查看次数

标签 统计

c# ×1

integer-arithmetic ×1

types ×1