Accessing form1 variables from another class how?

2020-04-23 03:25发布

how do I access form1 string variable from a different class?

 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.
}

标签: c# winforms
4条回答
冷血范
2楼-- · 2020-04-23 03:45

default value is set a every new instance if you want to keep last value you make a static property

 public static string deva = "123";
查看更多
Rolldiameter
3楼-- · 2020-04-23 03:51

Answer on the title question.
Read Jon Skeet's comment for explanation of reason why your approach not workiing.

If you want have access to the variables of another instance, then you need in someway have reference to that instance

One way pass it in the constructor of Other

public class Other: Form1
{
    private readonly Form1 _Form1;

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

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

Then where you create new instance of Other pass instance of your Form1 ti the constructor of Other

public class Form1
{
    private void button9_Click(object sender, EventArgs e)
    {
        Other ks = new Other(this);
        ks.test_me();
    } 
}
查看更多
我想做一个坏孩纸
4楼-- · 2020-04-23 03:57
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();
}
}

no need to inherit from form1, please pass the object via constructor

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

 }
}
查看更多
甜甜的少女心
5楼-- · 2020-04-23 04:05

Make your variable deva Static. Access it with Class directly not object.

public static string deva = "123";

public void test_me()
 {
     //Form1 fm = new Form1();
     MessageBox.Show(Form1.deva);

 }
查看更多
登录 后发表回答