问题描述
我有一个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
一个接口