How to add a delegate to an interface C#

前端 未结 6 1863
无人及你
无人及你 2021-01-30 07:42

I need to have some delegates in my class.

I\'d like to use the interface to \"remind\" me to set these delegates.

How to?

My class look like this:

6条回答
  •  青春惊慌失措
    2021-01-30 08:47

    The interface inherited within your derived class will remind you to define and link up the stuff you declared in it.

    But you may also want to use it explicitly and you will still need to associate it to an object.

    For example using an Inversion of Control pattern:

    class Form1 : Form, IForm {
       public Form1() {
         Controls.Add(new Foo(this));
       }
    
       // Required to be defined here.
       void IForm.Button_OnClick(object sender, EventArgs e) {
         ...
         // Cast qualifier expression to 'IForm' assuming you added a property for StatusBar.
         //((IForm) this).StatusBar.Text = $"Button clicked: ({e.RowIndex}, {e.SubItem}, {e.Model})";
       }
     }
    

    You can try something like this.

    interface IForm {
      void Button_OnClick(object sender, EventArgs e);
    }
    
    
    class Foo : UserControl {
      private Button btn = new Button();
    
      public Foo(IForm ctx) {
         btn.Name = "MyButton";
         btn.ButtonClick += ctx.Button_OnClick;
         Controls.Add(btn);
      }
    }
    

提交回复
热议问题