如何从main.class调用

本文关键字:class 调用 main | 更新日期: 2023-09-27 18:21:40

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

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

在我的主类中,我尝试过这样做:我还尝试过将修饰符更改为public,这样我就可以使用子类中的listbox。。

Class1 zz = new Class1();
zz.Display();

我的问题是如何将Display从子类调用到我的主类??我刚接触C#,非常感谢你的帮助D

如何从main.class调用

我猜"main class"指的是Form1。您在Display中所做的是创建一个新的(不可见)Form1(注意Form1 z = new Form1()中的new)。相反,您应该将当前可见Form1的引用传递给方法:

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

在您的Form1代码中:

Class1 zz = new Class1();
zz.Display(this);

确保您的子类设置为public。

public class Class1 {
    public void Display {
    }
}

然后你可以从你的主类调用该类

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