c# Access类型在另一个表单中



我有一个Form1和Form2,两者都是活动的和运行的,我可以同时改变两者的值,并希望从活动Form2访问(读写)活动Form1中的布尔值和整数。

现在我读到有多种方法可以达到这个目的,我想知道哪一种是最好的和最容易使用的?

1:在Form1中声明布尔值为静态值:

//Form2
if(MyProject.Form1.boolean1 = true)
{
MyProject.Form1.integer1 = 2;
}
//Form1
public static bool boolean1 = true;
public static int integer1 = 1; //changes to 2

2:声明公共变量

//Form2
private Form1 form1 = new Form1();
if(form1.boolean1 = true)
{
form1.integer1 = 2;
}
//Form1
private bool boolean1 = true;
public bool Boolean1
{
get
{
return this.boolean1;
}
}
private int integer1 = 1;
public int Integer1
{
get
{
return this.integer1;
}
set
{
this.integer1 = value;
}
}

3:初始化表单

//Form2
private Form1 form1 = new Form1();
if(form1.boolean1 = true)
{
form1.integer1 = 2;
}
//Form1
public bool boolean1 = true;
public int integer1 = 1; //changes to 2

4: Direct Initialize

//Form2
if(new Form1().boolean1 = true)
{
new Form1().integer1 = 2;
}
//Form1
public bool boolean1 = true;
public int integer1 = 1; //changes to 2

如果我初始化一个Form1作为新的形式,这是否意味着它将创建一个新的形式,不使用已经改变的值从我的活动Form1,但使用默认的静态int和bool值从Form1?

我该如何解决这个问题,是否有比上述方法更好的方法?

谢谢你的帮助:)

不要使用静态路由,因为变量显然属于表单。

我不知道你在尝试用这两种初始化路线,但它们也不正确。

那就只剩下公共属性了。但是你可以简化你的代码,在这里你不需要它们有私有的后台字段。

// The get is public, but the set can only be used within Form1
public bool Boolean1 { get; private set; }  
//    
public int Integer1 {get; set;}

相关内容

最新更新