且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问开放的形式方法从父窗体C#

更新时间:2023-12-06 13:20:52

声明一个方法public是不是一个好的做法。您可以创建委托或事件来代替。您可以创建公共委托该方法,并从执行该委托类外还可以创建事件,你可以处理从类的外部。

declaring a method public is not a good practice. you can create delegate or event instead. you can create public delegate for that method and execute that delegate from the outside the class Or you can create Event that you can handle from the outside of the class.

public partial class Form1 : Form
{
    public delegate void dMyFunction(string param);
    public dMyFunction delMyFunction;

    public Form1()
    {
        InitializeComponent();
        delMyFunction = new dMyFunction(this.MyFunction);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2();
        frm.Show();
    }
    private void MyFunction(string param)
    {
        this.Text = param;
    }
}

现在,你可以调用该委托从类的外部

Now, you can call this delegate from the outside the class

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

    private void Form2_Load(object sender, EventArgs e)
    {
        Form1 frm = (Form1)Application.OpenForms["Form1"];
        frm.delMyFunction.Invoke("Hello");
        //On Form load this method will be invoked and Form1 title will be changed.
    }
}