[英]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.在 Blazor 组件中,可以像在典型的 C# 类中一样创建用于方法的泛型参数。 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.但我想知道如何在 C# 类中尽可能地限制它。 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 .../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:但是在
.Clone()
我收到以下错误:
'modelType' does not contain a definition for 'Clone' ...
“modelType”不包含“克隆”的定义...
'.../GESD.Blazor/Shared/GesdTrForm.razor' creates a partial class called 'GesdTrForm' under the namespace 'GESD.Blazor.Shared'. “.../GESD.Blazor/Shared/GesdTrForm.razor”在命名空间“GESD.Blazor.Shared”下创建一个名为“GesdTrForm”的分部类。 Because it's a partial class, you can create a .cs file, delare the class as partial, and put the constraint in there.
因为它是一个部分类,所以您可以创建一个 .cs 文件,将该类声明为部分类,然后将约束放在那里。
.../GESD.Blazor/Shared/GesdTrForm.cs .../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.对于未来的搜索者,我刚刚发现 .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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.