如何静态获取枚举值

本文关键字:获取 枚举 静态 何静态 | 更新日期: 2023-09-27 18:01:04

我想静态地获取EnumMember的值。如果我通过填写我的模型,它就会起作用,如下所示。

LibraryStatus枚举

public enum LibraryStatus
{
    Watching, 
    Completed,
    [EnumMember(Value = "On Hold")]
    OnHold,
    Dropped,
    [EnumMember(Value = "Plan To Watch")]
    PlanToWatch
}

类别

public class LibraryListing
{
    ...
    [JsonConverter(typeof(StringEnumConverter))]
    public LibraryStatus LibraryStatus { get; set; }
    ...
}

当我通过模型查看时:

var initialData = @Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));

JSON输出

[{"AnimeListId":2146,"LibraryStatus":"On Hold","AnimeAccountId":3},{"AnimeListId":2165,"LibraryStatus":"Plan To Watch","AnimeAccountId":3},{"AnimeListId":2145,"LibraryStatus":"Watching","AnimeAccountId":3},{"AnimeListId":2174,"LibraryStatus":"On Hold","AnimeAccountId":3},{"AnimeListId":2143,"LibraryStatus":"Watching","AnimeAccountId":3},{"AnimeListId":2171,"LibraryStatus":"Dropped","AnimeAccountId":3}]

查看"LibraryStatus"键,它的值为"On Hold">

然而,当我打这样的电话时:

var output = Enum.GetValues(typeof(LibraryStatus));

输出为:

[0] => "Watching",
[1] => "Completed",
[2] => "OnHold", *****
[3] => "Dropped",
[4] => "PlanToWatch" *****

我基本上需要静态的枚举名称。如何使输出匹配?或者更好的是,有人有更好的方法/建议吗?我基本上需要输出,这样我就可以过滤视图上的数据。

如何静态获取枚举值

试试这个:

private List<String> GetEnumNames(Type enumType)
{
    return enumType.GetMembers(BindingFlags.Public | BindingFlags.Static).Select(m => { 
        var attr = m.GetCustomAttribute<EnumMemberAttribute>();
        if (attr != null)
            return attr.Value;
        return m.Name;
    }).ToList();
}

运行:

var output = GetEnumNames(typeof(LibraryStatus));
output.Dump();

给我输出:

Watching 
Completed 
On Hold 
Dropped 
Plan To Watch