如何从Form1访问Form2中的类值? C#

问题描述:

我有一个快速问题。我在Form2中创建了一个名为MyObject的类,其中有两个变量。按下一个按钮,Form2中的变量被改变。现在我的问题是如何在Form1中检索MyObject?这里是我的示例代码:

I have a quick question. I created a class in the Form2 called "MyObject" which has two variables in it. On the push of a button, the variables in Form2 are changed. Now my question is how to retrieve MyObject in Form1? Here is my sample code:

Form1

 public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f = new Form2(this);

        f.ShowDialog();
        ??????? (how can I retrieve Myobject here?????) 
    }

Form2



Form2

public class MyObject
    {
        public int Value1 { get; set; }
        public int Value2 { get; set; }

    }
    public Form2(Form1 frm1)
    {
        InitializeComponent();

    }
    private void button1_Click(object sender, EventArgs e)
    {
        MyObject obj = new MyObject();
        obj.Value1 = 102;
        obj.Value2 = 50;
    }

感谢大家

这样做

Form1

 public Form1()
 {
    InitializeComponent();
 }

 private void button1_Click(object sender, EventArgs e)
 {
    Form2 f = new Form2(this);

    f.ShowDialog();
    MyObject mo = f.GetMyObject;
 }

Form2

public Form2(Form1 frm1)
{
    InitializeComponent();
}

public MyObject GetMyObject 
{ 
    get
    {
        return obj;
    } 
}

MyObject obj;

private void button1_Click(object sender, EventArgs e)
{
    obj = new MyObject();
    obj.Value1 = 102;
    obj.Value2 = 50;
}

MyObject

public class MyObject
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }

}