在表单C#之间传递数据

时间:2015-11-29 21:03:44

标签: c#

我有三种不同形式的游戏。我保存每个级别的完成时间,并希望在第4个表单上访问它。我做到了这一点:

public partial class Results : Form
{
    public int  time1, time2, time3;
    FormLevel1 rez1 = new FormLevel1();
    FormLevel2 rez2 = new FormLevel2();
    FormLevel3 rez3 = new FormLevel3();

    public Results()
    {
        InitializeComponent();


    }
    void Calculations()
    {
        time1 = rez1.levelTime;
        time2 = rez2.levelTime;
        time3 = rez3.levelTime;
        MessageBox.Show(time1.ToString());
        MessageBox.Show(time2.ToString());
        MessageBox.Show(time3.ToString());
    }
}

我全部为零。我想我做错了什么。我该如何正确解决这个问题? 感谢。

2 个答案:

答案 0 :(得分:1)

FormLevel1 rez1 = new FormLevel1();
FormLevel2 rez2 = new FormLevel2();
FormLevel3 rez3 = new FormLevel3();

您正在创建三种表单的新实例,而不是使用"之前的"你想要使用的实例。

您需要(例如)公共财产通过3"之前的"形成Form4的实例(或实现相同的任何方法)。

但实际上,考虑一下你真正需要传递给你的表单结果:从你的代码中,你似乎只需要传递3个整数(levelTime为每个表单)

[编辑] 现在就意识到你的time1,time3和time3成员变量是公开的。 因此,在调用代码中,您可以执行以下操作:

Result resForm = new Result();
resForm.time1 = ... // have you saved result of form1 in a variable? use it here!
resForm.time2 = ... // same for form2
resForm.time3 = ... // same for form3
resForm.ShowDialog();

答案 1 :(得分:0)

让我试着解释一下你在这里做错了什么(基于我对你Calculations()所在位置的假设。如果我错了,请原谅我。)

public partial class Results : Form // (0)
{
    public int  time1, time2, time3;
    FormLevel1 rez1 = new FormLevel1(); //(1)
    ...

    public Results()
    {
        InitializeComponent(); 
        Calculations(); // (2) Assuming you call Calculations() here
    }

    void Calculations()
    {
        time1 = rez1.levelTime;
        MessageBox.Show(time1.ToString()); //(3)
        ...
    }
}

(0)在Time = 0时,您创建了Results类实例

(1)在Time = 0,您创建了FormLevel1类实例

(2)在时间= 0时,进行计算()

(3)在Time = 0时,显示FormLevel1的levelTime的消息框

即。 (0)到(3)发生在(差不多) SAME 时间!您FormLevel1没有机会完成定时器内容之前 Results执行其Calculation(),因此messageBox显示为0。

如果没有您解释更多关于您要在此处实现的内容或向我们提供您的FormLevel代码,我们无法为您提供更具体的解决方案。

一个可能的解决方案是从Results.Calculation() 之后致电FormLevels他们完成定时器工作。

如何?

public partial class Results : Form 
{
    ...
    FormLevel1 rez1 = new FormLevel1(this); //pass this instance of Results into FormLevel1
    ...

    public void Calculations() //Add public keyword so that it is accessible from FormLevel1
    {
        ...
    }
}

public partial class FormLevel1: Form 
{
    Results resultForm;

    public FormLevel1(Results callingForm) //modify constructor to accept Results
    {
        resultForm = callingForm;  
    }

    void TimerCompleted() //Call this when Timer finish its stuff
    {
        resultForm.Calculations();
    }

    ...
}

请注意,这可能不是您想要的解决方案。但这通常是在表单之间传递数据的最简单方法,回答你的标题问题。 (FormLevel1现在可以访问其所有的callingForm的公共变量和方法)

希望这有助于您理解。