通用 Blazor 组件可以处理具有相同结构的多个类吗?

问题描述 投票:0回答:1

我创建了一个 Blazor 组件来处理编辑由类定义的数据库记录。 我希望重用此组件来编辑其他记录 - 具有相同的结构,但字段名称不同。 例如,这是我的类定义之一:

public class AccountTypeCode
{
    public int AccountTypeId { get; set; }
    [Required]
    public string AccountType { get; set; } = string.Empty;
    [Required]
    public string? AccountTypeDescription { get; set; } = string.Empty;
    public string AdditionalInformation { get; set; } = string.Empty;
    public int DisplayOrder { get; set; } = 0;
    public DateOnly? DateTerminated { get; set; }
}

另一个类可能引用 CustomerTypeIdCustomerTypeCustomerTypeDescription 等。

在我的组件的@code 部分中,我目前的代码如下:

if (recordEdit is not null && !string.IsNullOrEmpty(recordEdit.AccountType))
{
    onSaveButton(recordEdit.AccountType);
}

其中 recordEdit 的类型为 AccountTypeCode。

我想要做的是将 recordEdit.AccountType 替换为通用 recordEdit.RecordType

通过这样做,我可以多次重用我的组件,而不必为我想要编辑的每个表编写新组件。

这就是我的组件的样子:

enter image description here

c# class blazor dry
1个回答
0
投票

您可以使用接口或泛型类型并使用反射。

例如,创建一个

IRecordType
界面:

public interface IRecordType
{
    string RecordType { get; set; }
    string? RecordDescription { get; set; }
    string AdditionalInformation { get; set; }
    int DisplayOrder { get; set; }
    DateOnly? DateTerminated { get; set; }
}

现在您应该实现它相关的类(对于

AccountTypeCode
CustomerTypeCode
,如果这是它的类名):

public class AccountTypeCode : IRecordType
{
    public int AccountTypeId { get; set; }
    [Required]
    public string AccountType { get; set; } = string.Empty;
    [Required]
    public string? AccountTypeDescription { get; set; } = string.Empty;
    public string AdditionalInformation { get; set; } = string.Empty;
    public int DisplayOrder { get; set; } = 0;
    public DateOnly? DateTerminated { get; set; }

    // here is the implementation of the interface properties
    string IRecordType.RecordType
    {
        get => AccountType;
        set => AccountType = value;
    }
    string? IRecordType.RecordDescription
    {
        get => AccountTypeDescription;
        set => AccountTypeDescription = value;
    }
}

现在在您的 razor 组件中添加

@typeparam
指令,基本上为组件声明一个名为 TRecordType 的通用类型参数。它允许组件使用特定类型,该类型将在使用组件时指定: @using System.Reflection @typeparam TRecordType where TRecordType : class, IRecordType, new() @* Some razor markup... *@ @code{ private TRecordType recordEdit = new(); }

因此,通常这允许您使用接口的 
RecordType

RecordDescription
属性,而不是特定类的属性(
例如。
AccountType
AccountTypeDescription
)。
例如在您的表单组件中:

<div> <label>Record Type *</label> <InputText @bind-Value="recordEdit.RecordType" /> </div> <div> <label>Record Description *</label> <InputText @bind-Value="recordEdit.RecordDescription" /> </div>

另外请考虑重构您的类和属性名称,最好将您的 id 属性命名为 
Id

,将您的类名称从

AccountTypeCode
更改为
AccountType
,并将此上下文中的
AcountType
字符串更改为
AccountTypeName
字符串。
希望这有帮助。

编辑

以这种方式使用或调用您的组件:

<GenericEditComponent TRecordType="AccountTypeCode" /> <GenericEditComponent TRecordType="CustomerTypeCode" />

	
© www.soinside.com 2019 - 2024. All rights reserved.