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 之后添加代码并在其中写入继承代码解决了问题,但我想知道在剃刀文件中是否可能具有多个接口继承?

解决方法

在C#中不能多重继承,并且Blazor模板生成C#类。因此,您不能inherits多个基类。但是,您可以@implements多个接口。

一个例子如下:

@implements IEventListener
@implements IInterface

我想这只是术语上的混乱。您inherit一个类,但您implement一个接口