简体   繁体   中英

Can a generic type parameter in a Blazor component be constrained?

In a Blazor component, you can create a generic parameter for use in a method just as you can in a typical C# class. To do this, the syntax is:

@typeparam T

But I would like to know how to constrain it as you can in a C# class. Something like

// pseudocode
@typeparam T : ICloneable 

For instance, I had the need to create the following component that allows a developer to pass a "Model" of generic type:

.../GESD.Blazor/Shared/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();
    }

}

But at .Clone() I get the following error:

'modelType' does not contain a definition for 'Clone' ...

'.../GESD.Blazor/Shared/GesdTrForm.razor' creates a partial class called 'GesdTrForm' under the namespace 'GESD.Blazor.Shared'. Because it's a partial class, you can create a .cs file, delare the class as partial, and put the constraint in there.

.../GESD.Blazor/Shared/GesdTrForm.cs

using System;

namespace GESD.Blazor.Shared {

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

}

For future searchers, I have just found that this feature is available in .NET 6.

Usage looks like:

@typeparam T where T : IMyInterface

If the generic type cannot be determined by the compiler then it can be specified explicitly:

<MyComponent T=MyType>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM