首页 > 解决方案 > 全局变量改变另一个类的值(C#)

问题描述

我是 c# 的新手,我正在制作一个程序,它在开始时有一个菜单按钮,按下时将全局 bool 变量设置为 true。此变量在另一个论坛中使用,但即使在按下按钮时它设置为 true,它也会将自身更改为 false

在第一个论坛中,全局变量为真(我在调试模式下运行它)。

在第二个论坛,全局变量不知什么原因变成了false。

这是在forum1上按下按钮时的代码(确认是forum2)

private void GButton_Click(object sender, EventArgs e)
    {
        this.Green = true;
        this.Hide();
        Confirmation confirmation = new Confirmation();
        confirmation.Show();
    }

这是使用其他论坛中的全局变量运行 if 语句时的代码(菜单是 forum1)

 public Confirmation()
    {
        InitializeComponent();
        Menu menu = new Menu();
        if(menu.Green == true)
        {
            //Set properties for green confirmation box
        }

全局布尔变量:

public bool Green { get; set; }

我怎样才能解决这个问题?非常感谢任何帮助。

标签: c#

解决方案


你想做的是:

public partial class Menu : Form
{
    public Menu()
    {
        InitializeComponent();
    }

    Confirmation confirmationForm;
    private void btnRed_OnClick(object sender, EventArgs e)
    {
        if (confirmationForm == null)
        {
            confirmationForm = new Confirmation();

            // if you need for the current Menu form to be hidden, 
            // you would need Confirmation form to be aware of it. That way
            // you can make Menu form visible when Confirmation form is
            // closed. You would need to write code in Form_Closed event.
            confirmationForm.Menu = this;

            // since you mentioned background color would be changed, 
            // if thats the only thing, you could just set that property.
            confirmationForm.BackColor = Color.Red;

            // or if you have other bunch of properties that needs 
            // to be set or logic that needs to be run, 
            // you could create a method in Confirmation
            confirmationForm.SetProperties("red");
        }

        // you may want to use ShowDialog(), so that you 
        // wont have multiple instances of confirmation being created.
        confirmationForm.Show();

        // so that it appears in the front.
        confirmationForm.BringToFront();

        this.Hide();
    }
}

在您的确认表中,您需要:

public partial class Confirmation : Form
{
    public Form Menu {get; set;}
    public Confirmation()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

    }

    public void SetProperties(string color)
    {
       // do your logic here 
    }

    private void Confirmation_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (Menu != null)
        {
            Menu.Show();
            Menu.BringToFront();
        }
    }
}

如果我理解正确,这应该会有所帮助,否则请在评论中告诉我。我很乐意帮助您理解这一点。


推荐阅读