在 Windows 运行时组件中无法继承? [英] Inheritance impossible in Windows Runtime Component?

查看:40
本文介绍了在 Windows 运行时组件中无法继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:
我的 Windows 运行时组件项目中有 3 个类(A、B、C).

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:

"不一致的可访问性:基类 'A' 的可访问性低于'C' 类."

"Inconsistent accessibility: base class 'A' is less accessible than class 'C'."

如果我公开 A 类,它会给出一个编译错误:

If I make class A public, it gives a compile error :

"不支持导出未密封的类型.请标记类型'MyProject.A' 已密封."

"Exporting unsealed types is not supported. Please mark type 'MyProject.A' as sealed."

但是现在,如果我将 A 设为密封,那么 B 和 C 就不能继承它.

But now, if I make A as sealed, then B and C cannot inherit from it.

考虑到只允许继承 WinRT 类型的事实,是否可以使用自定义/用户定义的类进行继承?如果没有,是否有任何解决方法可以实现相同的目标?

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?

推荐答案

正如您自己发现的那样,您不能在 Windows 运行时组件中公开从其他人继承的类;即使您尝试使用抽象类作为父类也是如此.这是使 WinRT 组件与 WinRT 框架支持的所有其他语言一起工作所需的缺点".解决此问题的唯一方法是避免继承.您只能使用可以模拟继承行为的接口或对象组合,例如:

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();
    }
}

这篇关于在 Windows 运行时组件中无法继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆