为什么不是int之外的整数类型尝试的数学运算时一样C#抛铸造错误? [英] Why does C# throw casting errors when attempting math operations on integer types other than int?

查看:143
本文介绍了为什么不是int之外的整数类型尝试的数学运算时一样C#抛铸造错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个静态的测试类:

 公共静态类测试
{
公共静态USHORT总和(USHORT值1,USHORT值2)
{
返回值1 +值2
}
}

这将导致以下编译错误,用值1 +值2 红色下划线:



< BLOCKQUOTE>

无法隐式转换类型'诠释'
到'USHORT。显式转换
存在(是否缺少强制)?




为什么?


< DIV CLASS =h2_lin>解决方案

像C和C ++在它之前,整数与隐许多运营商使用时扩大。在这种情况下,增加了两个 USHORT 值加在一起的结果是 INT



更新:



更多信息:的 http://msdn.microsoft.com/en-us/library/aa691330(v = VS.71)的.aspx



我相信这是最初在加入C / C ++,因为 INT 是一个原生的整数类型(是的,手术均在 INT 快总比在在32位架构的短 S)。我不能确定为C#的全部理由。



这确实让你觉得溢出/截断考虑当你施展。意外溢出更可能与较小的整数类型。


Consider this static test class:

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

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

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

Why?

解决方案

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.

Update:

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

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天全站免登陆