Blazor 组件中的泛型类型参数是否可以受到约束?

pwi*_*cox 8 generics components blazor

在 Blazor 组件中,您可以创建一个通用参数以在方法中使用,就像在典型的 C# 类中一样。为此,语法是:

@typeparam T
Run Code Online (Sandbox Code Playgroud)

但我想知道如何像在 C# 类中那样约束它。就像是

// pseudocode
@typeparam T : ICloneable 
Run Code Online (Sandbox Code Playgroud)

例如,我需要创建以下组件,允许开发人员传递通用类型的“模型”:

.../GESD.Blazor/共享/GesdTrForm.razor

@typeparam modelType

<EditForm Model="@Model" 
    OnValidSubmit="@OnValidSubmit"
    style="display:table-row"
>
    @ChildContent
</EditForm>

@code {

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public modelType Model { get; set; } // here is the use of the generic

    [Parameter]
    public EventCallback<EditContext> OnValidSubmit { get; set; }

    void demo () {
        var cloned = Model.Clone();
    }

}
Run Code Online (Sandbox Code Playgroud)

但在.Clone()我收到以下错误:

“modelType”不包含“Clone”的定义...

Ste*_*eve 17

对于未来的搜索者,我刚刚发现.NET 6 中提供了此功能。

用法如下:

@typeparam T where T : IMyInterface
Run Code Online (Sandbox Code Playgroud)

如果编译器无法确定泛型类型,则可以显式指定:

<MyComponent T=MyType>
Run Code Online (Sandbox Code Playgroud)


pwi*_*cox 1

'.../GESD.Blazor/Shared/GesdTrForm.razor' 在命名空间 'GESD.Blazor.Shared' 下创建一个名为 'GesdTrForm' 的分部类。因为它是一个分部类,所以您可以创建一个 .cs 文件,将该类指定为分部类,然后将约束放入其中。

.../GESD.Blazor/共享/GesdTrForm.cs

using System;

namespace GESD.Blazor.Shared {

    public partial class GesdTrForm<modelType> where modelType : ICloneable {}

}
Run Code Online (Sandbox Code Playgroud)