在Blazor组件中,您可以创建一个泛型参数,以便在方法中使用,就像在典型的C#类中一样。要做到这一点,语法是:
@typeparam T
但是,我想知道如何在C#类中尽可能地约束它。有点像
// pseudocode
@typeparam T : ICloneable
例如,我需要创建允许开发人员传递泛型“模型”的以下组件:
.../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();
}
}
但是在.Clone()
,我得到了以下错误:
“modelType”不包含“克隆人”的定义.
发布于 2022-01-15 02:31:13
对于未来的搜索者,我刚刚发现这个特性是.NET 6中的.NET。
用法如下:
@typeparam T where T : IMyInterface
如果编译器无法确定泛型类型,则可以显式地指定它:
<MyComponent T=MyType>
发布于 2020-10-27 10:58:22
‘./GESD.BLazor/Shared/GesdTrForm.Lazor’在命名空间'GESD.Blazor.Shared‘下创建一个名为'GesdTrForm’的部分类。因为它是一个分部类,所以您可以创建一个.cs文件,将类删除为分部,并将约束放在其中。
.../GESD.Blazor/Shared/GesdTrForm.cs
using System;
namespace GESD.Blazor.Shared {
public partial class GesdTrForm<modelType> where modelType : ICloneable {}
}
https://stackoverflow.com/questions/64561203
复制