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

标签 c# winforms

如何从不同的类访问 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/

相关文章:

c# - MouseEventHandler 附加参数 - 无法定义 "sender"和 "e"

c# - 升级现有应用程序以包含 ClickOnce

c# - 在 WPF 中筛选 DataGrid

winforms - 如何在 winforms 列表框中创建 "drag target line"来显示放置源是在放置目标之前还是之后被删除

winforms - WinForms 中 MessageBox 的任何好的替代品?

c# - 使用 Rx 进行上下文菜单操作

c# - .Net Core 2.0 中的 Windows 和匿名身份验证

c# - 休眠任务(System.Threading.Tasks)

C# LinearGradientBrush 位图垂直重复

c# - 标签在 ToolStrip 上方不可见