为什么在对int以外的整数类型进行数学运算时,C#会抛出转换错误? [英] Why does C# throw casting errors when attempting math operations on integer types other than int?

查看:146
本文介绍了为什么在对int以外的整数类型进行数学运算时,C#会抛出转换错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个静态测试类:

public static class Test
{
    public static ushort sum(ushort value1, ushort value2)
    {
        return value1 + value2
    }
}

这会导致以下编译错误, value1 + value2 下划线为红色:

This causes the following compile error, with value1 + value2 underlined in red:

无法将类型'int'
隐式转换为'ushort'。显示转换
存在(是否缺少转换)?

Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast)?

为什么?

推荐答案

像C和C ++之前,整数被隐式地扩大,当使用许多运算符。在这种情况下,将两个 ushort 值加在一起的结果是 int

Like C and C++ before it, integers are implicitly widened when used with many operators. In this case, the result of adding two ushort values together is int.

更新:

详细信息: http://msdn.microsoft.com/en-us/library/aa691330(v = VS.71).aspx < a>

More information: http://msdn.microsoft.com/en-us/library/aa691330(v=VS.71).aspx

我相信这是最初添加在C / C ++,因为 int 是一个本机整数类型,在 int 上的操作比在32位体系结构上的 short 更快)。我不确定C#的完全理由。

I believe this was originally added in C/C++ because int was a native integer type (and yes, operations were faster on ints than on shorts on 32-bit architectures). I'm unsure of the full rationale for C#.

它让你考虑溢出/截断的注意事项。意外溢出更可能与较小的整数类型。

It does make you think about overflow/truncation considerations when you cast. Accidental overflow is more likely with the smaller integer types.

这篇关于为什么在对int以外的整数类型进行数学运算时,C#会抛出转换错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆