Skip to main content
 首页 » 编程设计

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

2024年02月05日11bjzhanghao

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