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

后端 未结 5 1871
清酒与你
清酒与你 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 20:07

    Properties aren't fields either, although they feel like them. They are actually a pair of methods (getter and setter) with special syntax.

    Events are similarly a pair of methods (subscribe and unsubscribe) with special syntax.

    In both cases, you usually have a private "backing field" inside your class, which holds the value manipulated by the getter/setter/subscribe/unsubscribe methods. And there's an auto-implemented syntax for both properties and events where the compiler generates the backing field and accessor methods for you.

    The purpose is also the same: Properties provide restricted access to a field, where some validation logic is run before storing a new value. And an event provides restricted access to a delegate field, where consumers can only subscribe or unsubscribe, not read the list of subscribers, nor replace the whole list at once.

提交回复
热议问题