简体   繁体   中英

Which is the correct/better way of Delegate declaration

I noticed most of the developers are using event for callback and I'm not sure whether I'm doing in a right way.

I noticed most of developers' codes look like this:

public delegate void SampleDelegate();
public static event SampleDelegate SampleEvent;

While the way I do "event" look like this:

public delegate void SampleDelegate();
public SampleDelegate SampleEvent; // notice that I didn't set to static and not an event type

I hope someone could explain to me what's the differences between both codes? Which way of doing delegate is a better practice? Is it better to set it as a static?

Let's look at your code:

public delegate void SampleDelegate();
public SampleDelegate SampleEvent;

It's not an event. Because you can call SampleEvent outside the containing class:

public class TestClass
{
    public delegate void SampleDelegate();
    public SampleDelegate SampleEvent;
}

public void TestMethod()
{
    var a = new TestClass();
    a.SampleEvent();
}

Also, you can set it to new value:

public void TestMethod()
{
    var a = new TestClass();
    a.SampleEvent = null;
}

And this is not the event behavior. An interface can not contain this "event":

public interface ITestInterface
{
    //TestClass.SampleDelegate SampleEvent; //does not compile
}

So the right way - to add event word for real events:

public class TestClass : ITestInterface
{
    public delegate void SampleDelegate();
    public event SampleDelegate SampleEvent;

    private void FireEvent()
    {
        var handler = SampleEvent;
        if (handler != null)
            handler();
    }
}

public interface ITestInterface
{
    event TestClass.SampleDelegate SampleEvent;
}

And now you can only call it from the containing class:

public void TestMethod()
{
    var a = new TestClass();
    //a.SampleEvent(); //does not compile
    a.SampleEvent += A_SampleEvent; //subscribe to event
}

private void A_SampleEvent()
{
    Console.Write("Fired"); //fired when FireEvent method called
}

So, you must uderstand difference between delegates and events. And choose the appropriate way for different situations: Events - when you need to nodify other classes (one or more) about some changes. Delegetes - when you just want to declare a method signature and pass the implementation from outside (simplified explanation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM