Events aren't fields - I don't get it

后端 未结 5 1873
清酒与你
清酒与你 2020-12-23 19:22

In C# in depth (an excellent book thus far), Skeet explains events aren\'t fields. I read this section many times and I don\'t understand why the distinction makes

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-23 19:49

    An event is an accessor for a delegate. Just like a property is an accessor for a field. With the exact same utility, it prevents code from messing with the delegate object. Like a property has a get and set accessor, an event has the add and remove accessor.

    It does behave somewhat different from a property, if you don't write the add and remove accessors yourself then the compiler auto-generates them. Including a private backing field that stores the delegate object. Similar to an automatic property.

    You don't do this often but it is certainly not unusual. The .NET framework pretty commonly does so, for example the events of the Winforms controls are stored in an EventHandlerList and the add/remove accessors manipulate that list through its AddHandler() and RemoveHandler() methods. With the advantage that all the events (there are many) require only a single field in the class.

提交回复
热议问题