我有一个包含enum属性的类,在使用时序列化对象时JavaScriptSerializer,我的json结果包含枚举的整数值而不是它的string"name".有没有办法让枚举作为string我的json而不必创建自定义JavaScriptConverter?也许有一个属性,我可以装饰enum定义,或对象属性,?
举个例子:
enum Gender { Male, Female }
class Person
{
int Age { get; set; }
Gender Gender { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
期望的json结果:
{ "Age": 35, "Gender": "Male" }
Run Code Online (Sandbox Code Playgroud) 我想知道是否可以获取枚举值的属性而不是枚举本身的属性?例如,假设我有以下枚举:
using System.ComponentModel; // for DescriptionAttribute
enum FunkyAttributesEnum
{
[Description("Name With Spaces1")]
NameWithoutSpaces1,
[Description("Name With Spaces2")]
NameWithoutSpaces2
}
Run Code Online (Sandbox Code Playgroud)
我想要的是枚举类型,产生2元组的枚举字符串值及其描述.
价值很容易:
Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
foreach (int value in values)
Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value);
Run Code Online (Sandbox Code Playgroud)
但是如何获取描述属性的值,以填充Tuple.Desc?如果属性属于枚举本身,我可以想到如何做到这一点,但我不知道如何从枚举的值中获取它.
可能重复:
通过其描述属性查找枚举值
我有一个通用的扩展方法,它Description从以下方式获取属性Enum:
enum Animal
{
[Description("")]
NotSet = 0,
[Description("Giant Panda")]
GiantPanda = 1,
[Description("Lesser Spotted Anteater")]
LesserSpottedAnteater = 2
}
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
Run Code Online (Sandbox Code Playgroud)
所以我可以......
string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
Run Code Online (Sandbox Code Playgroud)
现在,我正试图在另一个方向上找出等效函数,比如......
Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
Run Code Online (Sandbox Code Playgroud) 如何使用枚举实现以下功能.NET?我想对每个包含空格的值进行描述.
public enum PersonGender
{
Unknown = 0,
Male = 1,
Female = 2,
Intersex = 3,
Indeterminate = 3,
Non Stated = 9,
Inadequately Described = 9
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在每次使用此类型的值时选择是使用描述还是整数.