首页 > 解决方案 > Blazor razor 文件中接口的多重继承

问题描述

我有一个 Blazor 组件,它只有一个 razor 文件(后面没有 razor.cs 代码),并且希望从接口继承该组件,首先我尝试了以下操作:

MyComponent.razor:

  @inherits IMyInterface

然后在构建之后,我在 .cs 生成的代码(由 Visual Studio 生成)中出现错误,我意识到该组件只是从我的接口而不是ComponentBase类派生的。这是生成的代码:

...
public partial class MyComponent: IMyInterface
    {
        #pragma warning disable 1998
        protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
        {
        }
        #pragma warning restore 1998
    }
...

所以我得到了“找不到合适的方法来覆盖”错误。

然后我尝试了以下代码并得到了所有这些代码的编译错误:

// 1) multiple inheritance
@inherits ComponentBase,IMyInterface

// 2) adding semicolon 
@inherits ComponentBase,IMyInterface;

// 3) mutiple @inherits directive
@inherits ComponentBase
@inherits IMyInterface

通过在文件MyComponent.razor.cs后面添加代码并在那里编写继承代码解决了这个问题,但我想知道是否可以在 razor 文件中对接口进行多重继承?

标签: c#asp.net-corerazorblazormultiple-inheritance

解决方案


在 C# 中不能进行多重继承,并且 Blazor 模板会生成 C# 类。所以你不能有inherits多个基类。但是,您可以使用@implements多个接口。

一个例子如下:

@implements IEventListener
@implements IInterface

我想这只是对术语的混淆。你inherit是一个类,但你implement是一个接口


推荐阅读