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);
}
}
}
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
に and not 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 に答える