【问题标题】:How to get items of enum in c#? [duplicate]如何在 C# 中获取枚举项? [复制]
【发布时间】:2021-04-30 01:49:43
【问题描述】:

我想根据枚举对象描述在 Razor 页面中创建一个选择选项

这是我的代码:

<div class="dropdown-box">
    <select id="type-select">
        @foreach (var item in Enums.OrderStatus)
        {
            <option>@item</option>
        }
    </select>
</div>

和枚举:

public enum OrderStatus
{
    [Description("در انتظار تایید")]
    PendingForAccept = 0,

    [Description("تمام شده")]
    Finished = 1,

    [Description("لغو شده")]
    Canceled = 2,

    [Description("رد شده")]
    Rejected = 3,

    [Description("تایید شده")]
    Accepted = 4
}

如何将此枚举的项目描述提取到字符串

【问题讨论】:

标签: c# asp.net razor enums razor-pages


【解决方案1】:

这是一个执行此操作的代码示例。

public static string ExtractDescription<T>(T enumVal) where T : struct
{
    var type = enumVal.GetType();
    if (!type.IsEnum)
    {
        throw new ArgumentException($"{nameof(enumVal)} must be an Enum", nameof(enumVal));
    }

    var memberInfo = type.GetMember(enumVal.ToString());
    if (memberInfo.Length > 0)
    {
        var attributes = memberInfo[0].GetCustomAttributes(attributeType: typeof(DescriptionAttribute), inherit: false);

        if (attributes.Length > 0)
        {
            return ((DescriptionAttribute)attributes[0]).Description;
        }
    }

    return enumVal.ToString();
}

用法:

var s = ExtractDescription(OrderStatus.PendingForAccept)// s is "در انتظار تایید"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2014-02-02
    • 2011-07-07
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多