using System;
using System.Drawing;
using System.Windows.Forms;
namespace Test
{
class mainWindow : Form
{
public mainWindow()
{
Label firstLabel = new label();
firstLabel.Text = "Hello";
this.Controls.Add(firstLabel);
Button firstButton = new Button();
firstButton.Text = "Click me";
firstButton.Click += firstButton_Click;
firstbutton.Left = 100;
this.Controls.Add(firstButton);
}
void firstButton_Click(object sender, EventArgs e)
{
firstlabel.Text = "Goodbye";
}
}
class XxX
{
static void Main()
{
mainWindow form = new mainWindow();
Application.Run(form);
}
}
}
user1924485
问问题
1561 次
2 回答
3
因为是一个作用域为构造函数firstLabel
的局部变量。mainWindow
您可以创建班级firstLabel
的私人成员mainWindow
:
class mainWindow : Form
{
private Label firstLabel;
public mainWindow()
{
firstLabel = new Label();
firstLabel.Text = "Hello";
this.Controls.Add(firstLabel);
Button firstButton = new Button();
firstButton.Text = "Click me";
firstButton.Click += firstButton_Click;
firstbutton.Left = 100;
this.Controls.Add(firstButton);
}
void firstButton_Click(object sender, EventArgs e)
{
firstLabel.Text = "Goodbye";
}
}
此外,大多数类是传统的PascalCased
而不是camelCased
(即class MainWindow
代替mainWindow
)。
于 2012-12-23T04:31:01.867 回答
-1
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Test
{
class mainWindow : Form
{
// since u need to access the control, u need to keep that control at global level
private Button firstButton = null;
private Label firstLabel = null;
public mainWindow()
{
firstLabel = new Label();
firstLabel.Text = "Hello";
Controls.Add(firstLabel);
Button firstButton = new Button();
firstButton.Text = "Click me";
firstButton.Click += firstButton_Click;
firstButton.Left = 100;
Controls.Add(firstButton);
}
void firstButton_Click(object sender, EventArgs e)
{
// now since the variable is global u can access it and change the title
firstLabel.Text = "Goodbye";
}
}
static class XxX
{
static void Main()
{
mainWindow form = new mainWindow();
Application.Run(form);
}
}
}
于 2012-12-23T04:33:27.857 回答