如何静态获取Enum值?

时间:2015-07-06 00:03:17

标签: c# json asp.net-mvc enums json.net

我想静态获得EnumMember的价值。如果我填写我的模型,它就可以工作,如下所示。

LibraryStatus Enum

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" *****

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

1 个答案:

答案 0 :(得分:3)

试试这个:

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