Skip to main content
 首页 » 编程设计

c#之child 和 parent 如何沟通

2024年02月24日23over140

假设我有一个表格和他的 child 我希望 child 在他们不认识的情况下触发他的父亲 换句话说,我希望 child 是通用的

例如,假设我有一个表单按钮和一个 richTextBox,我想通过每次单击来更改 richTextBox 文本

我想让表单和按钮互不认识,我该怎么做? 我试试这个:

public partial class Form1 : Form 
{ 
 
    delegate void myfatherDelgate(); 
    static int msgCounter = 0 ; 
 
    public Form1() 
    { 
        InitializeComponent(); 
        button1 = new myButton(); 
        myfatherDelgate += myMethod(); 
 
    } 
    public void myMethod() 
    { 
        switch (msgCounter) 
        { 
            case 1: 
                { 
                    richTextBox1.Text = "first click"; 
                    msgCounter++; 
                } 
            case 2: 
                { 
                    richTextBox1.Text = "second click"; 
                } 
            defult: this.Close; 
        } 
 
 
 
    } 
 
 
} 

公共(public)类 mybutton : 按钮 { 静态 int myint;

    protected override void OnClick(EventArgs e) 
    { 
        base.OnClick(e); 
        this.Parent.Invoke(myfatherDelgate()); 
    } 
 
 
} 

最简单的方法是:

    private void button1_Click(object sender, EventArgs e) 
    { 
        switch (msgCounter) 
        { 
            case 1: 
                { 
                    richTextBox1.Text = "first click"; 
                    msgCounter++; 
                } 
            case 2: 
                { 
                    richTextBox1.Text = "second click"; 
                } 
            defult: this.Close; 
        } 
    } 

以父亲的形式...

我认为我的所有概念都是废话,有人可以照亮我吗? 但我在这里弄错了,它是圆形的,有人可以帮我吗?...

请您参考如下方法:

所以也许您正在寻找的更多是接口(interface)实现:

public interface IMyInterface { 
    void MyAction(); 
} 
 
public partial class form1 : Form, IMyInterface { 
    public void MyAction() { 
        richTextBox1.Text = "first click"; 
        ... 
    } 
} 
 
public class button1 : Button { 
    protected override void OnClick(EventArgs e) { 
        var parent = this.Parent as IMyInterface; 
        if( parent != null ) { 
            parent.MyAction(); 
        } 
    } 
}