generics - 将枚举传递给 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”的无效转换。
解决方案
您需要EnumType
在生命周期OnInitialized(){ ... }
或OnInitializedAsync(){ ... }
.
参考文档:https ://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-3.1
推荐阅读
- flutter - 如何在 Flutter 中将 API 模型对象存储在本地存储中?
- drop-down-menu - 从包含重复值的下拉列表中选择一个值
- mysql - Update index values extremely slow on MySQL
- java - 获取文档参数的网页脚本
- javascript - 通过控制台触发使用淘汰赛js创建的元素的更改事件
- next.js - 如何使用 next.config.js 中的 pwa 和 i18n 模块在 Next js 上离线运行 PWA?
- javascript - 获取 vue 项目中所有路线的列表并生成站点地图 - Vue Project
- git - 用空的 git commit 触发 CI/CD 有什么意义?
- c# - 需要在 C# 中调整高分辨率图像(300 dpi)的大小
- javascript - 导入本地下载的 pdfjs 库