Sealed method in C#

后端 未结 7 1701
萌比男神i
萌比男神i 2020-12-13 13:15

I am a newbie in C#.I am reading about Sealed keyword.I have got about sealed class.I have read a line about Sealed method where we can make Sealed method also.The line was

7条回答
  •  被撕碎了的回忆
    2020-12-13 13:19

    A sealed class is a class which cannot be a base class of another more derived class.

    A sealed method in an unsealed class is a method which cannot be overridden in a derived class of this class.

    Why do we use sealed methods? What are the advantages of sealed methods?

    Well, why do you use virtual methods? To provide a point at which behaviour of a class can be customized. So why do you use sealed methods? To provide a point at which you are guaranteed that no further changes will occur in the behaviour of any derived class with respect to this method.

    Points where the behaviour of a class can be customized are useful but dangerous. They are useful because they enable derived classes to change behaviour of the base class. They are dangerous... wait for it... because they enable derived classes to change behaviour of the base class. Virtual methods basically allow third parties to make your classes do crazy things that you never anticipated or tested.

    I like writing code that does what I anticipate and what I tested. Sealing a method allows you to continue to allow parts of the class to be overridden while making the sealed methods have guaranteed, testable, stable behaviour that cannot be further customized.

提交回复
热议问题