What is the preferred event handling method in C #?

What is the preferred / recommended way to handle events in .NET:

this.Load += new EventHandler(Form1_Load);
private void Form1_Load(object sender, EventArgs e)
{ }

or

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
}

What are the pros / cons of each method? I used both methods over the years and usually leaned more toward the first method simply because this is what Visual Studio automatically creates to handle events. Are there any advantages to the second method that I am missing?

+3
source share
5 answers

The first way is what Microsoft offers. Template:

  • some code wants to raise an event, calls OnXxx
  • OnXxx makes a call to the delegate
  • Wired event handlers are called

, base.OnXxx . 2 , , . base.OnXxx, , . , , - , .

+8

, .

() - , - . ; , - . , , , .

() , , , ; .

+5

, , :

this.Load += new EventHandler(Form1_Load);

:

this.Load += Form1_Load;

.

+1

, . , .

+ = , . , . , , "n" , . - + = , .

OnXXXX

, base.XXX. , Windows , - Windows ( ..).

0

, CLR.

[Edit] , :

:

class Foo
{
    public event EventHandler Changed = delegate { };

    protected virtual void OnChanged()
    {
        this.Changed(this, EventArgs.Empty);
    }
}

class Bar : Foo
{
    public Bar()
    {
        this.Changed += new EventHandler(this.Bar_Changed);
    }

    void Bar_Changed(Object sender, EventArgs e) { }
}

class Baz : Foo
{
    protected override void OnChanged() 
    { 
        base.OnChanged();
    }
}

, Baz - , . Bar IL :

    L_000a: ldftn instance void Bar::Bar_Changed(object, class [mscorlib]System.EventArgs)
    L_0010: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int)
    L_0015: call instance void Foo::add_Changed(class [mscorlib]System.EventHandler)

, EventHandler, add_Changed . , Baz Baz . OnChanged , CLR, .

-1

Source: https://habr.com/ru/post/1703044/


All Articles