Difference in invoking through Delegates and Events C#

后端 未结 5 902
天命终不由人
天命终不由人 2021-01-13 22:11

What is the difference?

Using Delegate

public delegate void TestDelegate();
public TestDelegate delObj = SomeMethod;

public void S         


        
5条回答
  •  天涯浪人
    2021-01-13 23:15

    An event declaration is really just a special kind of property that's used to expose a delegate. Instead of get and set accessors, though, it creates add and remove ones. Normally they're implemented automatically, but if you desire you can add custom behavior:

    private MyEventHandler handler;
    public event MyEventHandler MyEvent {
        add {
            handler += value;
            Trace.WriteLine("MyEvent handler attached.");
        }
        remove {
            handler -= value;
            Trace.WriteLine("MyEvent handler removed.");
        }
    }
    

    This does two things. First, since events are properties they can be included in interfaces. Second, since MyEvent does not return a value, the delegate is completely encapsulated and only the object that owns it can invoke it. Other ways of exposing delegates result in a delegate that can be invoked by just about anyone.

    Beyond that bit of special language support, the other major difference between events and delegates is a convention rather than a language or framework feature: Events are expected to follow certain patterns, such as making sure that the delegate on which the event is based follows the pattern established by the EventHandler delegate.

    Generally, events are preferred whenever the semantics are that of an object notifying anyone who's interested about a change in its stage. Delegates are preferred in situations where you want others to be able to define behavior by supplying their own procedure, such as the delegate parameters that are taken by many of the extension methods on IEnumerable that are used in LINQ.

提交回复
热议问题