C# 调用其他表单方法
我有两张表格,表格一和表格二。表格1将用于初始化表格2。初始化表单2之后,表单2将调用表单1方法,但它就是不起作用。我已经搜索了几个小时,但仍然不知道它是如何工作的。请帮帮我 表格一C# 调用其他表单方法,c#,winforms,C#,Winforms,我有两张表格,表格一和表格二。表格1将用于初始化表格2。初始化表单2之后,表单2将调用表单1方法,但它就是不起作用。我已经搜索了几个小时,但仍然不知道它是如何工作的。请帮帮我 表格一 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Lin
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace parentChildTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 x = new Form2();
x.Show();
}
public static void callMe(){
MessageBox.Show("HAHAHA");
}
}
}
表格二
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace parentChildTest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/*How to call callMe()?????*/
}
}
}
callMe是静态的,那么为什么需要创建新实例呢?静态方法可以在没有对象的情况下调用。我想继续使用旧的初始化Form1。不是新的对不起,伙计们……我刚才很模糊…………现在肯定有用了。谢谢你叫醒我。我没有注意到它已经是正确的。如果要使用form1的实例,请将其传递到form2构造函数中,将实例另存为变量,然后在引用上调用该方法,无需再次初始化form1。只需使用其类名调用函数。静态方法可以用类名直接调用。当您想从callMe中删除静态时,您的问题会变得稍微复杂一些,但是有大量的研究资料可以帮助您
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.Callme();
}
}
private void button1_Click(object sender, EventArgs e)
{
Form1.callMe();
}