c# - 全局变量改变另一个类的值(C#)
问题描述
我是 c# 的新手,我正在制作一个程序,它在开始时有一个菜单按钮,按下时将全局 bool 变量设置为 true。此变量在另一个论坛中使用,但即使在按下按钮时它设置为 true,它也会将自身更改为 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; }
我怎样才能解决这个问题?非常感谢任何帮助。
解决方案
你想做的是:
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();
}
}
}
如果我理解正确,这应该会有所帮助,否则请在评论中告诉我。我很乐意帮助您理解这一点。
推荐阅读
- java - 如何正确反编译java代码?
- database - 审计数据云存储有哪些好的选择?(连续写,很少查询)
- android - Android 项目在 Android Studio 4.0.1 编译时无法运行
- jquery - 如何处理重新加载站点jquery的取消按钮
- php - 我可以在我的 SQL 查询中添加一个具有自动递增值的临时列来补充我的 for 循环吗?
- flutter - 将小部件分组以作为一个滚动
- android - 'onPrepareOptionsPanel(View?, Menu): Boolean' 已弃用。在 Java 中已弃用
- windows - 在 windows docker 中分离图像和容器数据
- python - 需要在子列表中找到最小的数字,其中数字是字符串格式
- python - 无法正确打印组列表,还破坏了获取功能?