Why seal a class?

前端 未结 10 1893
醉酒成梦
醉酒成梦 2020-11-28 04:51

I\'d like to hear what is the motivation behind the bulk of sealed classes in the .Net framework. What is the benefit of sealing a class? I cannot fathom how not allowing in

相关标签:
10条回答
  • 2020-11-28 05:41

    Sealing allows you to realize some minor performance gains. This is less true in the world of JITs and lazy pessimization than in the world of, say C++, but since .NET is not as good as pessimization as java compilers are mostly because of different design philosophies it is still useful. It tells the compiler that it can directly call any virtual methods rather than call them indirectly through the vtable.

    It is also important when you want a 'closed world' for things like equality comparison. Normally once I define a virtual method, I'm pretty much hosed for defining a notion of equality comparison that really implements the idea. On the other hand, I might be able to define it for a particular subclass of the class with the virtual method. Sealing that class ensures that equality really does hold.

    0 讨论(0)
  • 2020-11-28 05:42

    Sealing a class makes managing disposable resources easier.

    0 讨论(0)
  • 2020-11-28 05:47

    A further consideration is that sealed classes can't be stubbed in your unit tests. From Microsoft's documentation:

    Sealed classes or static methods can't be stubbed because stub types rely on virtual method dispatch. For such cases, use shim types as described in Using shims to isolate your application from other assemblies for unit testing

    0 讨论(0)
  • 2020-11-28 05:54
    • Sometimes classes are too precious and not designed to be inherited.
    • Runtime/Reflection can make inheritance assumptions about sealed classes when looking for types. A great example of this is - Attributes are recommended to be sealed for lookup runtime speed. type.GetCustomAttributes(typeof(MyAttribute)) will perform significantly faster if MyAttribute is sealed.

    The MSDN article for this topic is Limiting Extensibility by Sealing Classes.

    0 讨论(0)
提交回复
热议问题