c# - Windows 运行时组件中不可能继承?

标签 c# windows windows-runtime win-universal-app winmd

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

class A{}
public sealed class B : A {}
public sealed class C : A {}

编译上述代码时,出现以下错误:

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

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

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

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

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

最佳答案

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

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

关于c# - Windows 运行时组件中不可能继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36334929/

相关文章:

c - 串行端口 : Read data problem with loopback, 未读取任何内容

c# - 本地部署和从应用商店部署时的不同应用行为

c# - 在 Visual Studio 2012 中发布时为 "target location"设置默认文件夹

c# - 引用的 XmlSchemaElement 中的 IsAbstract 值不正确

c++ - #include <windows.h> 导致很多语法错误

c# - 如何在 Windows Phone 8.1 通用应用程序中获取街道地址的地理定位?

c# - 是否有可能从 Windows 8 商店应用程序 (C#) 启动另一个应用程序或程序

c# - Linq2SQL : Select only some columns, 但仍然可以提交更改

c# - EF 4 和 POCO 的最佳实践/入门解决方案

c# - 向用户显示文件无法加载到程序 C# 的消息