在C#中的if中创建对象的实例 [英] Creating an instance of an object within an if in C#

查看:440
本文介绍了在C#中的if中创建对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在if语句中创建对象的实例吗?
我已经制作了2个复选框以控制我使用的构造函数,但是我收到错误消息名称mth在当前上下文中不存在

Can I create an instance of an object within an if statement? I've made 2 checkboxes in order to controll which constructor I use, but i get the error message " The name "mth" does not exist in the current context "

if (checkBox1.Checked && checkBox2.Checked)
        {
            Facto mth = new Facto(label3, wait_time, progressBar1);
        }
        else if(checkBox1.Checked==false && checkBox2.Checked)
        {
            Facto mth = new Facto(label3,wait_time);
        }
        else if (checkBox1.Checked && checkBox2.Checked == false)
        {
            checkBox1.Checked = false;
            Facto mth = new Facto();
        }
        else
        {
            Facto mth = new Facto();
        }


        int result = mth.Factorial(number);

我做错了什么?我是C#的新手,我还没有真正掌握它。
任何帮助将不胜感激。
提前致谢。

What am I doing wrong? I'm new to C# and I don't really have the hang of it yet. Any help would be appreciated. Thanks in advance.

推荐答案

这是一个范围问题。变量mth仅存在于其定义的范围(在您的情况下为括号)中。一旦离开范围,变量就不再可用。由于您在代码末尾(以及范围之外)使用 mth 变量,因此会出现此错误。为了解决这个问题,您需要在更高的范围内定义变量。请注意,您不必在那里分配它。

This is a scoping problem. The variable mth only exists within the scope (brackets in your case) that it's defined in. As soon as you leave the scope the variabel is no longer available. Since you use the mth variable at the end of your code (and outside the scope) you get this error. In order to fix this you need to define the variable at a higher scope. Note that you don't have to assign it there.

这会产生类似的结果(请注意,我重新格式化了括号,以便更容易看到范围级别)

This leads to something like (Note that I reformatted your brackets to make it easier to see the scope levels)

    Facto mth; // Define it as the most outer scope level you are using it
    if (checkBox1.Checked && checkBox2.Checked)
    {
         mth = new Facto(label3, wait_time, progressBar1);
    }
    else 
        if(checkBox1.Checked==false && checkBox2.Checked)
        {
            mth = new Facto(label3,wait_time);
        }
        else 
            if (checkBox1.Checked && checkBox2.Checked == false)
            {
                checkBox1.Checked = false;
                mth = new Facto();
            }
            else
            {
                mth = new Facto();
            }

   int result = mth.Factorial(number);

编辑:我建议总是在每个if和else上使用{}括号,即使它们不是严格按照您的情况要求。正如你在布局中看到的那样,不容易看到你的第一个结束的地方,并且int结果行不是它的一部分。

I would advice to always use {} brackets on every if and else even if they are not strictly required like in your case. As you can see in the layout it's not so easy to see where your first else ends and that the "int result line isn't part of it.

这篇关于在C#中的if中创建对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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