如何将枚举字符串值发送到客户端

本文关键字:客户端 字符串 枚举 | 更新日期: 2023-09-27 18:25:56

我定义了一个枚举如下。

public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

我正在把它寄回客户。

public List<Month> GetMonths()
{
    return Enum.GetValues(typeof(Month)).Cast<Month>().ToList();
}

然而,我在客户端收到的是0,1,2,3,....11 values,而不是实际的字符串值,即月份名称。

如何将实际月份名称作为值发送?

如何将枚举字符串值发送到客户端

您可以在Enum:上使用GetNames方法

public string[] GetMonths()
{
    return Enum.GetNames(typeof(Month));
}

Newtonsoft.Json.Converters提供StringEnumConverter。

用法:

[JsonConverter(typeof(StringEnumConverter))]
public Enum SomeProperty { get; set; }

使用此代码获取字符串列表。

使用Enum静态方法方法GeNames。

List<string> monthsName =Enum.GetNames(typeof(Month)).ToList();