是否可以从方法中定义类作用域对象

本文关键字:定义 作用域 对象 方法 是否 | 更新日期: 2023-09-27 18:12:40

这似乎是完全不合理的要求,但我一直在设计一个多面板,真正的设备模拟器,它有许多不同的屏幕,我目前的方法是添加所有的屏幕对象从代码,并在我切换到另一个屏幕时处理它们。

我有一些固定的对象,那是真正的设备按钮,已经定义和到位。事情是,我在方法中分离每个面板结构,例如:buildLogin(), buildMainScreen()等,我需要从这些方法中编辑一些屏幕对象,例如将启用的功能标签的颜色更改为绿色(如果启用)或白色(如果禁用)。

我的问题是:是否有可能从一个可以在整个类中访问的方法中声明一个对象,就像它在变量声明部分定义一样?它类似于PHP中的GLOBAL。

我不能像以前那样在所有东西的最上面声明它,因为当我处置对象时,我不能"重新创建"它们,因为养育,或者重用处置过的对象或其他原因…

示例代码:
public partial class frmMain : Form
{
    //I could as well do this:
    //Button button1 = new Button();
    public frmMain()
    {
         buildLogin();
    }
    private void buildLogin()
    {
        Panel panel1 = new Panel();
        Controls.Add(panel1);
        //But then, there is no way to do this:
        // if (button1.IsDisposed == true) //because of the panel, or smthing
        Button button1 = new Button();
        panel1.Controls.Add(button1);
        button1.Click += (s, f) => { panel1.Dispose(); buildMainMenu(); };
    }
    private void buildMainMenu()
    {
        Panel panel2 = new Panel();
        Controls.Add(panel2);
        Button button2 = new Button();
        panel2.Controls.Add(button2);
    }
    //This was created from the Designer and is class-scoped
    private void btn_Frame_TSK1_Click(object sender, EventArgs e)
    {
        //Here, I have no access to the objets I've created programatically.
        //button1.Text = "Text changed!";
    }
}

是否可以从方法中定义类作用域对象

如果你想确保事情总是完全动态的,并且总是在后面的代码中完成,你可能想看看搜索你在controls集合中创建的控件。

例如,确保给button1一个ID值(button1.ID="textUpdatedButton"),这将使它与您创建的其他控件区分开来。然后在Controls集合上使用FindControl或搜索来查找具有您希望在事件处理程序中定位的ID的控件。

//This was created from the Designer and is class-scoped
private void btn_Frame_TSK1_Click(object sender, EventArgs e)
{
    Control control = this.FindControl("textUpdatedButton");
    if(control != null && control is Button){
        Button button1 = (Button)control;
        button1.Text = "Text changed!";
    }
}

或者,为了使它看起来更像一个变量,您可以使用Property来隐藏控件查找(如前所述):

private Button Button1 {
    get { return (Button)this.FindControl("textUpdatedButton"); }
}
//This was created from the Designer and is class-scoped
private void btn_Frame_TSK1_Click(object sender, EventArgs e)
{
    if(this.Button1 != null){
        this.Button1.Text = "Text changed!";
    }
}

实际实现将随您如何构建控件而变化,但本质上,如果您需要这样做,这种方法可以让您在代码中动态构建所有内容。请记住使用标识符,以便以后查找。

在类级别定义对象为Static。这样就可以从类的所有实例的所有方法中访问它(处置一个实例不会影响它)。