Difference in invoking through Delegates and Events C#

后端 未结 5 898
天命终不由人
天命终不由人 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 22:55

    C# has a lot of constructs that don't add anything new to the language, but are simply syntactic sugar for a construct, because the construct requires some pattern of code which is tiresome to type every time over and over again. For example the using statement is equivalent of a try-finally block with a call to the dispose method, and properties are just syntactic sugar for an get and/or set method.

    In a similar way events are just syntactic sugar for a delegate field. There are some subtle differences however, which others have mentioned. Since a public field isn't recommended, the delegate would have to be encapsulated and a nice way of doing that is with an event. And (as Mark mentions) the event is only invokable from inside of the class.

    I usually choose between delegate field and event based on what I conceptually think the field or event should represent. If it represents something anyone would want to be notified of, I'd recommend the event. Otherwise if it represents for example a function to acquire a result, I'd use a delegate field.

提交回复
热议问题