为什么我不能用这个按钮改变这个标签?

本文关键字:改变 标签 按钮 为什么 不能 | 更新日期: 2023-09-27 17:49:24

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);  
        }  
    }
}  

为什么我不能用这个按钮改变这个标签?

因为firstLabelmainWindow构造函数作用域的局部变量。您可以使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)。

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);
        }
    }
}