Why do WinRT types have to be sealed?

2019-04-20 22:31发布

问题:

In several places (e.g. "Creating Windows Runtime Components for JavaScript, in C# and Visual Basic" on MSDN), I've seen it specified that, if you write a class in .NET that you want to use from JavaScript, then you must make it a sealed class.

This seems like an arbitrary restriction. Why can JavaScript only work with sealed classes?

回答1:

Windows runtime objects exposed to JavaScript applications are sealed from a JavaScript perspective - you can't add expando properties to WinRT objects. But from C++ and C#, winrt objects can be inherited if the object supports inheritance (most Xaml classes support inheritance for instance, but most others don't).

The reason that WinRT objects are sealed from JS is to ensure that the winrt object behave the same regardless of what the app has done - if an app redefines some function property on an object, it could cause other parts of the app to misbehave.