C#编译器尝试将简短结果转换为整数[duplicate]

问题描述 投票:0回答:1

我正在尝试使用2个short类型的数字执行模运算:

short short1 = 1; // or any other short value
short short2 = 2;
short result = short1 % short2;

但是我收到此编译错误:

无法将类型'int'隐式转换为'short'。一个明确的转化存在(您是否缺少演员表?)

为什么编译器认为结果应为int类型?结果必须在0到min(short1,short2)之间,并且两个值均为short

c# compiler-errors modulo
1个回答
0
投票

在您的情况下,请使用模块运算符将short编号提升为int 之前,因为没有为小于int的类型定义余数运算符。

所以您有int int.operator %(int left, int right),返回类型为int

您可以明确地转换为short,因为您知道结果可由short表示。

short result = (short)(short1 % short2);
© www.soinside.com 2019 - 2024. All rights reserved.