gpt4 book ai didi

c# - 如何从另一个类访问 form1 变量?

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:18 25 4
gpt4 key购买 nike

如何从不同的类访问 form1 字符串变量?

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

public string deva = "123";

//button
private void button8_Click(object sender, EventArgs e)
{
deva = "456";
}

private void button9_Click(object sender, EventArgs e)
{
Other ks = new Other();
ks.test_me();
}
}

public class Other: Form1
{
//trying to access Form1 variable.
public void test_me()
{
Form1 fm = new Form1();
MessageBox.Show(fm.deva);
//deva is 123 but not 456.
//I clicked on button and values changes it form1 however from here it assigns just default value
}

//
//Does creating a new form1 will reset its values?
//Somebody please help me. how to solve this issue.
}

最佳答案

public partial class Form1: Form {

public Form1()
{
InitializeComponent();
}
public string deva = "123";

//button
private void button8_Click(object sender, EventArgs e)
{
deva = "456";
}

private void button9_Click(object sender, EventArgs e)
{
Other ks = new Other(this);
ks.test_me();
}
}

无需继承form1,请通过构造函数传递对象

public class Other { 
Form1 obj = null;
public Other(Form1 object)
{
this obj = object;
}
public void test_me()
{
MessageBox.Show(obj.deva);

}
}

关于c# - 如何从另一个类访问 form1 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39716696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com