C# 在if语句中使用变量多次定义此成员
第一个按钮2和1在第一个和第二个if语句中获取此错误。 我怎样才能让他们工作? 提前谢谢C# 在if语句中使用变量多次定义此成员,c#,.net,C#,.net,第一个按钮2和1在第一个和第二个if语句中获取此错误。 我怎样才能让他们工作? 提前谢谢 private void button1_Click(object sender, EventArgs e) { if (button2 == true) { richTextBox1.AppendText(String.Format("Please continue with the midpoint.\n"));
private void button1_Click(object sender, EventArgs e)
{
if (button2 == true)
{
richTextBox1.AppendText(String.Format("Please continue with the midpoint.\n"));
}
else if(button2 == false)
{
richTextBox1.AppendText(String.Format("Type the first set of coordinates in.\n"));
bool button1 = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (button1 == true)
{
richTextBox1.AppendText(String.Format("Please continue with the distance.\n"));
}
else if(button1== false)
{
richTextBox1.AppendText(String.Format("Type the first set of coordinates in.\n"));
bool button2 = true;
}
}
}
}
我假设您已经在某个地方定义了一个bool值,在这种情况下,您不需要再次指定类型:
button1 = true
您需要在类级别将这些成员定义为
private
成员,并为其指定不同的名称/标识符,因为button1
和button2
很可能是您的按钮
控件名称
public class someclass
{
private bool mbutton2 = false;
private bool mbutton1 = false;
private void button1_Click(object sender, EventArgs e)
{
if (mbutton2)
{
richTextBox1.AppendText(String.Format
("Please continue with the midpoint.\n"));
}
else
{
richTextBox1.AppendText(String.Format
("Type the first set of coordinates in.\n"));
mbutton1 = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (mbutton1)
{
richTextBox1.AppendText(String.Format
("Please continue with the distance.\n"));
}
else
{
richTextBox1.AppendText(String.Format
("Type the first set of coordinates in.\n"));
mbutton2 = true;
}
}
}
您正在混合变量声明和值赋值Button1已经是按钮的名称,因此无法创建名为该名称的变量。与button2相同。您可以使用与成员相同的名称定义局部变量,您将得到警告,但不会出现编译器错误。您可以发布真实代码吗?如果
button1
或button2
是bool类型,为什么会有单击事件?我怀疑您将其简化得太多,从而损坏了代码。我得到了与此相同的错误。@Max,如果您进行所示的更改,则无法得到相同的错误。您可能会遇到另一个错误,在这种情况下,请与我们共享。@DavidArno我猜该错误类似于“不存在将bool转换为System.Windows.Forms.Button的隐式转换”或类似的错误。这仍然会产生错误,他已经有了另一个名为button1
和button2
的错误。名称需要不同。请参阅事件处理程序的声明,按钮本身的名称已经命名。@RonBeyer,答案是假设button1
或button2
不是他的按钮控件名称。如果是,那么他发布的代码实际上没有意义,因为按钮
控件无法分配bool
值。这就是为什么他会得到已经定义的错误(在问题的标题中)。
public class someclass
{
private bool mbutton2 = false;
private bool mbutton1 = false;
private void button1_Click(object sender, EventArgs e)
{
if (mbutton2)
{
richTextBox1.AppendText(String.Format
("Please continue with the midpoint.\n"));
}
else
{
richTextBox1.AppendText(String.Format
("Type the first set of coordinates in.\n"));
mbutton1 = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (mbutton1)
{
richTextBox1.AppendText(String.Format
("Please continue with the distance.\n"));
}
else
{
richTextBox1.AppendText(String.Format
("Type the first set of coordinates in.\n"));
mbutton2 = true;
}
}
}