作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 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' does not contain a definition for 'Clone' ...
最佳答案
对于以后的搜索者,我刚刚发现这个功能是available在 .NET 6 中。
用法如下:
@typeparam T where T : IMyInterface
如果编译器无法确定泛型类型,则可以显式指定:
<MyComponent T=MyType>
关于generics - Blazor 组件中的泛型类型参数可以受到约束吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64561203/
我是一名优秀的程序员,十分优秀!