如何将对象从 form1 传递到 form2 并返回到 form1? [英] How do you pass an object from form1 to form2 and back to form1?

查看:30
本文介绍了如何将对象从 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# 为紧凑型框架 2.0 编写应用程序.

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

我需要获取在 form1 上实例化的数据对象并将该对象传递给 form2.处理 form2 中的数据对象,然后将该数据传回 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.

实现这一目标的最佳、最简洁的代码方式是什么?

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

推荐答案

您需要做的是为您的第二个表单创建第二个构造函数,该构造函数接受一个对象作为参数...就我而言,它可能是整个 Form1 对象实例,然后您可以从中获取任何您想要的内容.以您的第二种形式保留此对象并根据需要在那里修改它.完成第二个表单后,您的第一个表单将包含该数据,并且您可以在第二个表单关闭后执行任何刷新"操作.

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";
    }


}

这篇关于如何将对象从 form1 传递到 form2 并返回到 form1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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