-1

我有我想从我的主类调用的代码:

public void Display()
{

    Form1 z = new Form1();

    z.listBox1.Items.Add("=============================Summary=============================\n\n");
    z.listBox1.Items.Add("1st: "+Num1+" 2nd #: "+Num2);
    z.listBox1.Items.Add("\n"+" 3rd #: "+Num3+" 4th #: "+Num4);
    z.listBox1.Items.Add("\n"+" 5th #: "+Num5);
    z.listBox1.Items.Add("\n" + "SUM: " + Sum + " DIFF: " + Sub + "\n" + " PROD: " + Multiply + " QOU: " + Divide);

    // result = ("=============================Summary=============================\n\n 1st #: " + Num1 + " 2nd #: " + Num2 + "\n 3rd #: " + Num3 + " 4th : " + Num4 + "\n 5th #: " + Num5 + "\n" + "SUM: " + Sum + " DIFF: " + Sub + "\n" + " PROD: " + Multiply + " QOU: " + Divide);

}

在我的主类中,我尝试这样做:并且我还尝试将修饰符更改为公共,这样我就可以使用我的子类中的列表框..

Class1 zz = new Class1();

zz.Display();

我的问题是如何Display从子类调用主类?我是 C# 的新手,非常感谢您的帮助。:D

4

2 回答 2

1

我猜你所说的“主类”是指你的 Form1。您正在做的Display是创建一个的(不可见的) Form1 (注意newin Form1 z = new Form1())。相反,您应该将当前可见的 Form1 的引用传递给该方法:

public void Display(Form1 z)
{
    z.listBox1.Items.Add("=============================Summary=============================\n\n");
    // etc.
}

在您的 Form1 代码中:

Class1 zz = new Class1();
zz.Display(this);
于 2013-07-09T06:49:08.200 回答
0

确保您的子类设置为公开。

public class Class1 {
    public void Display {

    }
}

然后你可以从你的主类中调用那个类

public class Main {
    public void SomeMethod() {
         Class1 zz = new Class1();

         zz.Display();
    }
}
于 2013-07-09T06:48:31.257 回答