从表单传递变量,无法在其他方法中使用

Passed Variable From Form, Unable to be used in other methods

没错,这应该是非常简单的事情,尽管由于某些原因我遇到了问题,

public partial class confSelMenu : Form
{
    public confSelMenu(string mainChoice, string secondChoice, int segNum)
    {
        InitializeComponent();
        int circSeg = segNum;
        label2.Text = mainChoice;
        label3.Text = secondChoice;
        label4.Text = segNum.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        int x1 = circSeg;  <---ERROR HERE

        switch (x1)
        {
            case 3:

                break;

            case 4:

                break;

            case 5:

                break;

            case 6:

                break;

            case 7:

                break;
       }

        wheelMenu wheelMen = new wheelMenu(x1, x2, x3);
        wheelMen.ShowDialog();
    }
}

我在 button_click1 事件 中收到错误,行为;

int x1 = circSeg

错误如下:

无法将类型 'System.Windows.Forms.Label' 隐式转换为 int

这里有一些背景信息:

我已经成功地将前一个表单中的 3 个变量传递到这个表单中,并将它们显示为表单中的标签(名字(字符串),姓氏(string), 3 - 7(int)),

如你所见,我在 label.Text 中使用它们,它们显示良好,

现在我正在尝试在事件(单击按钮)时发生切换情况,我希望它根据他们选择的 int 做一些不同的事情(在 3 - 7 之间)

但出于某种原因,我从 VS 2013 中收到此错误,有人可以帮忙吗?

非常感谢!

像下面这样尝试。

public partial class confSelMenu : Form
{
int circSeg;
public confSelMenu(string mainChoice, string secondChoice, int segNum)
{
    InitializeComponent();

    circSeg = segNum;
    label2.Text = mainChoice;
    label3.Text = secondChoice;
    label4.Text = segNum.ToString();

}

问题是您在构造函数中定义了它,而不是将其定义为实例字段。

Cannot Implicity Convert Type 'System.Windows.Forms.Label' into int

还想指出编译错误

您似乎在名为 circSeg 的表格上添加了标签。如果是这种情况,您需要更改实例字段或标签名称。

你的代码有问题

您在下面的方法中定义了 circSeg 变量并且

public confSelMenu(string mainChoice, string secondChoice, int segNum)
{    
    int circSeg = segNum;
}

在其他方法中访问它,这就是问题..如果你想访问相同的变量而不是你需要在 class 范围而不是方法范围

中定义该变量

所以你需要这样做

public partial class confSelMenu : Form
{
 private int circSeg;
  //other code
  void method1()
  {
     circSeg= value;
  }
}

在 class 级别范围内声明变量,而不是在方法级别范围内声明变量,这一点非常重要

这个与变量作用域相关的非常基本的问题,我建议您去阅读有关变量作用域的内容。