Inheritance impossible in Windows Runtime Component?

こ雲淡風輕ζ 提交于 2019-12-13 14:11:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!