为什么C#会发出错误“无法将int隐式转换为ushort"?反对在Ushorts上的模运算? [英] Why does C# issue the error "cannot implicitly convert int to ushort" against modulo arithmetic on ushorts?

查看:89
本文介绍了为什么C#会发出错误“无法将int隐式转换为ushort"?反对在Ushorts上的模运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个线程中,有人问为什么添加两个 ushort 值会引起C#错误.例如

In another thread, someone asked about why adding two ushort values raised errors in C#. e.g.

ushort x = 4;
ushort y = 23;
ushort z = x+y;  // ERROR cannot implicitly convert int to ushort 

在该线程上,人们争辩说plus +运算符默认情况下采用两个int,这是一种语言功能,可帮助避免算术溢出.但是我在以下函数中遇到了相同类型的错误:

On that thread, people argued that the plus + operater takes two ints by default, and this is a language feature to help avoid arithmetic overflows. But I get the same kind of error in the following function:

public RGB(ushort red, ushort green, ushort blue)
{
    // this class RGB has three ushort fields: r, g, and b
    r = red % ((ushort)256);
    g = green % ((ushort)256);
    b = blue % ((ushort)256);
}

编译器出错,并说无法将类型'int'隐式转换为'ushort'.存在显式转换...".但是这里的%模运算符可以防止溢出的说法根本没有任何意义:如果x和y是 ushort 值,则 x%y<max(x,y),因此没有溢出为整数的风险.那我为什么会收到这个错误?

where the compiler errors and says "Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists...". But here the argument that the modulo % operator is guarding against overflow doesn't make any sense at all: if x and y are ushort values, then x%y < max(x,y), so there is no risk of overflowing into ints. So why am I getting this error?

推荐答案

即使使用 shorts ushorts ,正在使用的%运算符也具有的签名.> int%(int a,int b).因此,您的短裤被提升为整数,结果是您试图分配给 ushort 的整数,这是有损的转换,因此您必须明确.

The % operator that's being used, even with shorts or ushorts, has a signature of int %(int a, int b). So your shorts are being lifted up into integers, and your result is an integer you are attempting to assign to a ushort, which is a lossy cast so you are required to be explicit.

考虑一下:

ushort x = 5;
ushort y = 6;
var res = x % y;
Console.WriteLine(res.GetType()); // System.Int32
ushort z = res; // cast error, explicit conversion exists
ushort zz = (ushort)res; // Fine, we cast down.

这篇关于为什么C#会发出错误“无法将int隐式转换为ushort"?反对在Ushorts上的模运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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