gpt4 book ai didi

generics - Blazor 组件中的泛型类型参数可以受到约束吗?

转载 作者:行者123 更新时间:2023-12-05 00:55:27 29 4
gpt4 key购买 nike

在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com