首页 > 解决方案 > 将枚举传递给 Blazor 组件的参数

问题描述

我有一个需要枚举作为参数的 Razor 组件。我已经读到您应该用来@typeparam传递泛型类型,但是当我使用变量名尝试它时EnumType,每次输入时都会出现以下错误EnumType

EnumType找不到类型或命名空间名称(您是否缺少 using 指令或程序集引用?

代码大致如下:

@typeparam TEnum


@foreach (EnumType flag in Enum.GetValues(typeof(EnumType)))
    {
        if (((EnumType)Old).HasFlag(flag))
        {
            if (((EnumType)New).HasFlag(flag))
            {
                <li>@EnumExtensions.GetEnumDisplayName(flag)</li>
            }
            else
            {
                <li class="deleted-li">@EnumExtensions.GetEnumDisplayName(flag)</li>
            }

        }
    }

@code{
    [Parameter]
    public TEnum EnumType { get; set; }
    //          ^ only time I dont get the error

    [Parameter]
    public int Old { get; set; }

    [Parameter]
    public int New { get; set; }
}

编辑:我休息了一会儿,然后回来查看我的代码,并意识到这毫无意义。我已经将它更新为类似于:

@typeparam TEnum

@foreach (Enum flag in Enum.GetValues(typeof(TEnum)))
    {
        if (((Enum)Convert.ChangeType(Old, typeof(TEnum))).HasFlag(flag))
        {
            if (((Enum)Convert.ChangeType(New, typeof(TEnum))).HasFlag(flag))
            {
                <li>@EnumExtensions.GetEnumDisplayName(flag)</li>
            }
            else
            {
                <li class="deleted-li">
                    @EnumExtensions.GetEnumDisplayName(flag) 
                 </li>
            }

        }
    }
@code{
    [Parameter]
    public int Old { get; set; }
    [Parameter]
    public int New { get; set; }
}

我现在在((Enum)Convert.ChangeType(Old, typeof(TEnum))说:

从“System.Int32”到“DataAccessLibrary.Enums.TimelineinfoEnums+MisconductEnum”的无效转换。

标签: genericsenumsblazorblazor-server-side

解决方案


您需要EnumType在生命周期OnInitialized(){ ... }OnInitializedAsync(){ ... }.

参考文档:https ://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-3.1


推荐阅读