C#从另一种形式创建类的新实例

时间:2018-07-05 12:59:18

标签: c# forms class oop

我对使用C#进行面向对象的编程完全陌生,并且想知道使用第二种形式输入细节的最佳方法是什么,该细节用于创建第一种形式上存在的对象的新实例。
 我是否只是将变量传递回表单并在新表单上创建新实例。只是想知道最好的方法。...

form1的基本代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.ShowDialog();
    }
}

class person
{
    public string Name { get; set; }
    public int age { get; set; }
}

Form2的基本代码

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // How do I create a new instance of person using these variables
        string name = "Neil";
        int age = 42;
        this.Close();
    }
}

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

在Form2类中,

首先包含Person类存在的名称空间 然后使用new关键字可以创建人员类别的实例

Person personObj = new Person();

如果要为Person类中存在的属性分配值,则

Person personObj = new Person()
{
    Name = "Nail",
    Age = 23
};

答案 1 :(得分:1)

您可以在Form2中创建一个对象,然后像这样在Form1中获取它:

    public partial class Form1 : Form
    {            

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            if (frm2.ShowDialog() == DialogResult.OK)
            {
                var p = frm2.Person;
            }
        }
   }


   public partial class Form2 : Form
   {
        public person Person { get; set; }            

        private void button1_Click(object sender, EventArgs e)
        {
            this.Person = new Person();
            //set properties in Person object
        }
    }

或者如果要将对象从Form1传递到Form2,在Form2中对其进行更新并重新获取Form1,则可以执行以下操作:

public partial class Form1 : Form
{
    private void button1_Form1_Click(object sender, EventArgs e)
    {
        var p = new Person();
        Form2 frm2 = new Form2(p);
        if (frm2.ShowDialog() == DialogResult.OK)
        {
            var updatedPerson = frm2.Person;
        }
    }
}

public partial class Form2 : Form
{
    public person Person { get; set; }
    public Form2(Person p)
    {
        this.Person = p;
        InitializeComponent();
    }
    private void button1_Form2_Click(object sender, EventArgs e)
    {
        //set properties of this.Person
    }
}