如何从Form1以Form2的传递一个对象并返回到Form1?

问题描述:

我已决定要求它做之前在这个问题上的一些研究。我无法找到任何帮助了我。

I have done some research on this question before deciding to ask it. I just could not find anything that helped me.

我写在C#应用程序的Compact Framework 2.0的。

I am writing an application in C# for the compact framework 2.0.

我需要实例化Form1上并通过对该对象的窗口2的数据对象。在窗口2中的数据对象的工作,然后传递数据返回到Form1,因此它可以被保存。

I need to take a data object instantiated on form1 and pass that object a form2. Work on the data object in form2 and then pass that data back to form1 so it can be saved.

据我所知,形式只是一个对象的我也明白,对象是过去的引用而不是价值。我也明白这两种类型之间的区别。我只是不能让它出于某种原因。

I understand that a form is just an object an I also understand that objects are past by reference and not by value. I also understand the difference between the two types. I just cannot make it work for some reason.

什么是最好的,干净的,方式code来实现这一目标?

What is the best, and cleanest, way in code to achieve this?

您需要做的是创建第二个构造你的第二个形式,接受一个对象作为参数......我都不在乎,也可能是整个Form1的对象实例,那么你可以得到任何你从它想要的。 preserve这个对象在你的第二个形式,并根据需要修改它在那里。当你的第二个表的完成,你的第一个形式将有这些数据,你可以做任何提神一旦第二窗体关闭。

What you need to do is create a second constructor to your second form that accepts an object as a parameter... for all I care, it could be the entire Form1 object instance, then you can get whatever you want from it. Preserve this object in your second form and modify it as needed there. Upon completion of your second form, your first form will have that data and you can do whatever "refreshing" once the second form closes.

public partial class YourSecondForm : Form
{
    object PreserveFromFirstForm;

    public YourSecondForm()
    {
       ... its default Constructor...
    }

    public YourSecondForm( object ParmFromFirstForm ) : this()
    {
       this.PreserveFromFirstForm = ParmFromFirstForm;
    } 

    private void YourSecondFormMethodToManipulate()
    {
       // you would obviously have to type-cast the object as needed
       // but could manipulate whatever you needed for the duration of the second form.
       this.PreserveFromFirstForm.Whatever = "something";
    }


}