如何从Form1访问Form2中的类值? C# [英] How to access class values located in Form2 from Form1? C#

查看:162
本文介绍了如何从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; }

}

这篇关于如何从Form1访问Form2中的类值? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆