问题
Scenario:
I have 3 classes (A,B,C) in my Windows Runtime Component project.
class A{}
public sealed class B : A {}
public sealed class C : A {}
On compiling the above code, I get the following error:
"Inconsistent accessibility: base class 'A' is less accessible than class 'C'."
If I make class A public, it gives a compile error :
"Exporting unsealed types is not supported. Please mark type 'MyProject.A' as sealed."
But now, if I make A as sealed, then B and C cannot inherit from it.
Considering the fact that only WinRT types are allowed for inheritance, is it anyhow possible to use custom/user-defined classes for inheritance? If not, is there any workaround to achieve the same?
回答1:
As you've figured out by yourself, you can't expose classes that inherit from others in a Windows Runtime Component; that is true even if you try to use an abstract class as a parent class. This is a "drawback" needed to make WinRT components works with all the others languages that the WinRT framework supports. The only way to workaround this is avoiding inheritance. You can only use interfaces or object composition where you can simulate inheritance behaviors, e.g.:
public sealed class A
{
public void Method() { }
}
public sealed class B
{
A a;
public void Method()
{
// Do B stuff
// Call fake "virtual" method
a.Method();
}
}
来源:https://stackoverflow.com/questions/36334929/inheritance-impossible-in-windows-runtime-component