简单的减法和强制转换问题 [英] Simple subtraction and cast question

查看:72
本文介绍了简单的减法和强制转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个简单的减法不起作用?

Why won't this simple subtraction work?

int MyPageNumber = Convert.ToInt32(cboPageNumber.SelectedItem);
MyPageNumber += (MyPageNumber - 1); //does not work
int MyNewPageNumber = MyPageNumber - 1; /works

我还希望有人能告诉我为什么这给了我一个红线能够进行转换:

I was also hoping someone could tell me why this gives me a "red line" for not being able to do a cast:

short MyPageNumber = Convert.ToInt16(cboPageNumber.SelectedItem);
MyPageNumber += MyPageNumber - ((short) 1); //does not work says can't cast

我不了解什么?在示例中+将它转换为字符串吗?

What am I not understanding? Is the + turning it into a String in the examples?

谢谢。

推荐答案

确切地查看其作用:

MyPageNumber += (MyPageNumber - 1); 

将MyPageNumber-1添加到现有值中。因此,如果MyPageNumber为5,则最终得到的是9,而不是您想要的4。

It adds MyPageNumber-1 to the existing value. So if MyPageNumber is 5, you end up with 9 instead of the 4 which you presumably want.

现在,第二个问题的情况基本上与

Now for the second problem, you've basically got a situation equivalent to this:

short x = 5;
short y = 10;
short z = x - y;

看起来不错,但是C#实际上没有短裤的减法运算符-它只有一个在整数上,因此它会将 x y 都隐式转换为 int 。结果也是 int ,您不能将其分配回 z 。您需要:

It looks okay, but C# doesn't actually have a subtraction operator for shorts - it only has it on ints, so it's implicitly converting both x and y to int. The result is then an int too, which you can't assign back to z. You need:

short z = (short) (x - y);

(或与您的实变量名称等效的变量)。

(or the equivalent with your real variable names).

这篇关于简单的减法和强制转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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