在不同的类之间调用函数

时间:2014-02-26 15:39:22

标签: c#

我习惯于编写嵌入式c并且不熟练使用c#。

我的问题是我希望能够从openAnotherForm()运行函数Welcome_Form,现在代码不起作用。我耐心地尝试了不同的事情,但只是设法让我感到沮丧。

我简化了相关代码以说明问题。

文件1 - 这将运行并打开文件2.

class UIcode
{
    private Welcome_Form Welcome;
    private AnotherForm_Form AnotherForm;

    public UIcode()
    {
        Welcome = new Welcome_Form();
        Application.Run(Welcome);
    }

    public void openAnotherForm()
    {
        Welcome.Hide();
        AnotherForm = new AnotherForm_Form();
        AnotherForm.ShowDialog();
    }
}

文件2 - 当我点击TheButton时,程序应该从文件1运行函数openAnotherFrom

public partial class Welcome_Form : Form
{
    public Welcome_Form()
    {
        InitializeComponent();
    }

    private void TheButton_Click(object sender, EventArgs e)
    {
        // Function from file 1
        UIcode.openAnotherForm();
    }
}

我意识到这个问题可能非常微不足道,但我仍然会对如何做到这一点的解释感激不尽。

优先:UIcode中的函数只能由UIcode指定的类识别。

3 个答案:

答案 0 :(得分:3)

您可以更改构造函数以引用打开它的UIcode实例:

    private static UIcode myParent;

    public Welcome_Form(UIcode parent)
    {
        myParent = parent;
        InitializeComponent();
    }

现在在UIcode中:

   public UIcode()
   {
        Welcome = new Welcome_Form(this);
        Application.Run(Welcome);
   }

最后,回到Welcome_Form

    private void TheButton_Click(object sender, EventArgs e)
    {
        // Function from file 1
        myParent.openAnotherForm();
    }

答案 1 :(得分:0)

您的openAnotherForm()方法不是static,因此需要实例引用才能使用。实例化UICode对象,或将方法标记为static

答案 2 :(得分:0)

您可以在File1中创建该类的实例以调用该方法。您已调用类UICode,因此应将构造函数从public UserInterface()重命名为public UICode()

class UIcode
{
    private Welcome_Form Welcome;
    private AnotherForm_Form AnotherForm;

    public UIcode() // Renamed Constructor
    {
        Welcome = new Welcome_Form();
        Application.Run(Welcome);
    }

    public void openAnotherForm()
    {
        Welcome.Hide();
        AnotherForm = new AnotherForm_Form();
        AnotherForm.ShowDialog();
    }
}

public partial class Welcome_Form : Form
{
    public Welcome_Form()
    {
        InitializeComponent();
    }

    private void TheButton_Click(object sender, EventArgs e)
    {
        // Create an instance UICode
        UICode instance = new UICode();

        // Call the method from the instance, not from the class.
        instance.openAnotherForm();
    }
}

或者,您可以使openAnotherForm()成为static方法,但您还需要制作实例变量(WelcomeAnotherFormstatic 。您还需要初始化它们,但您也可以通过构建构造函数static来实现它。

class UIcode
{
    private static Welcome_Form Welcome;
    private static AnotherForm_Form AnotherForm;

    public static UIcode() // Renamed Constructor
    {
        Welcome = new Welcome_Form();
        Application.Run(Welcome);
    }

    public static void openAnotherForm()
    {
        Welcome.Hide();
        AnotherForm = new AnotherForm_Form();
        AnotherForm.ShowDialog();
    }
}