如果语句不能更改局部变量 [英] If statement can't change local variable

查看:74
本文介绍了如果语句不能更改局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用if语句更改值?

Why can't i change value with an if statement?

        int amount;
        string inputbalk = inputbar.Text;

        if (inputbalk== string.Empty)
        {
            amount = Convert.ToInt32(inputbalk);
            amount = 1;
        }

        if (inputbalk != string.Empty)
        {
            amount = Convert.ToInt32(inputbalk);
            amount = 1;
        }

        int onepercent = amount/= 100;

即使我通过两个不同的if语句将其设置为1,也会将金额"视为未分配的变量.

It will see "amount" as an unassigned variable, even though I set it to 1, by two different if-statements.

如果我进行调试,则会得到以下信息: 错误1使用未分配的局部变量'amount'"

If I debug, I get this: "Error 1 Use of unassigned local variable 'amount'"

感谢帮助人员,此问题已修复/解决.

Thanks for help guys, It is fixed/solved.

推荐答案

如果不是,只需更改第二个

Just change second if to else

        if (inputbalk== string.Empty)
        {
            amount = Convert.ToInt32(inputbalk);
            amount = 1;
        }
        else
        {
            amount = Convert.ToInt32(inputbalk);
            amount = 1;
        }

编译器无法确保两个if语句之一仍然可以工作,因此会引发错误,提示您变量量可以是 unassigned.

The compiler can't make sure that one of two if statements will work anyway, so it will throw error that your variable amount can be unassigned.

if/else表示法中,无论如何都将完成两个代码块之一,因此编译器不会引发错误,一切都会按您的要求进行.

In if/else notation one of two code blocks will be done anyway, so compiler will not throw error and everything will work as you want.

这篇关于如果语句不能更改局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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