问题
VS compiler does not allow to create sealed exposed types for WINMD type library.
Why is this restriction placed ? (I know about sealed types advantages, my question is with respect to Win RT components).
回答1:
This is an architectural limitation, imposed by COM. Which sits at the core of any WinRT type, they are derived from IUnknown and IInspectable. The problem with COM is that it only supports interface inheritance but not implementation inheritance. Which was a strong COM design goal, implementation inheritance is too fraught with implementation details, including the infamous diamond problem.
There is a way to make inheritance work by delegation, each method in the derived class explicitly calls the corresponding base interface method, but that's very painful to do yourself. But otherwise the way that Windows.UI.Xaml classes implement inheritance.
回答2:
I believe the reason is because exposed types should be usable from all different kind of languages(C#, C++, JavaScript any maybe more in the future).
So if you have a class, then one of the use of a class is overriding it into new class. I could want to overide class, that is done in different language. But this is a problem. How do you want to override a base class done in C#, by inheritor class done in C++? This can never work, because both of those have completly different and incompatible OOP implementations.
By forcing exposed classes to be sealed, you remove this problem and make sure people won't try to do something like this.
I'm sure there are much more fundamental things than this, but this is what came to my mind first.
来源:https://stackoverflow.com/questions/10493865/why-exposed-types-must-be-sealed-for-winmd-winrt-components