首页 > 解决方案 > 另一个表单中的 C# 访问类型

问题描述

我有一个 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:直接初始化

 //Form2
if(new Form1().boolean1 = true)
{
   new Form1().integer1 = 2;
}

//Form1
public bool boolean1 = true;
public int integer1 = 1; //changes to 2

如果我将 Form1 初始化为新表单,这是否意味着它将创建一个新表单并且不使用我的活动 Form1 中已经更改的值,而是使用 Form1 中的默认静态 int 和 bool 值?

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

谢谢你的帮助 :)

标签: c#forms

解决方案


不要走静态路线,因为变量显然属于表单。

我不知道您在这两种初始化路线上都在尝试什么,但它们也不正确。

这样就只剩下公共属性的方式了。但是你可以简化你的代码,在这里你不需要他们有私有的支持字段。

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

//    
public int Integer1 {get; set;}

推荐阅读