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

时间:2016-09-27 05:34:39

标签: 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.
}

4 个答案:

答案 0 :(得分:3)

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);   

 }
}

答案 1 :(得分:1)

回答标题问题。
阅读Jon Skeet的评论,解释您的方法无法正常工作的原因。

如果您想要访问另一个实例的变量,那么您需要在某种程度上引用该实例

一种方法是在Other

的构造函数中传递它
public class Other: Form1
{
    private readonly Form1 _Form1;

    public Other(Form1 form1)
    {
        _Form1 = form1;
    }

    public void test_me()
    {
        MessageBox.Show(_Form1.deva);
    }
}

然后,您在Other的{​​{1}}传递实例Form1的新实例创建Other

的构造函数
public class Form1
{
    private void button9_Click(object sender, EventArgs e)
    {
        Other ks = new Other(this);
        ks.test_me();
    } 
}

答案 2 :(得分:0)

使变量 deva 静态。直接使用Class访问它而不是对象。

dist

答案 3 :(得分:0)

默认值设置每个新实例 如果您想保留最后一个值,则可以创建static属性

 public static string deva = "123";