相关疑难解决方法(0)

.NET - 枚举的jSON序列化为字符串

我有一个包含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)

c# asp.net enums json javascriptserializer

1088
推荐指数
22
解决办法
42万
查看次数

获得Enum价值的属性

我想知道是否可以获取枚举值的属性而不是枚举本身的属性?例如,假设我有以下枚举:

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?如果属性属于枚举本身,我可以想到如何做到这一点,但我不知道如何从枚举的值中获取它.

c# reflection enums .net-attributes

453
推荐指数
9
解决办法
27万
查看次数

从Description属性获取枚举

可能重复:
通过其描述属性查找枚举值

我有一个通用的扩展方法,它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 c# enums attributes

206
推荐指数
4
解决办法
18万
查看次数

如何使用空格枚举值?

如何使用枚举实现以下功能.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)

我希望能够在每次使用此类型的值时选择是使用描述还是整数.

.net c# vb.net enums

24
推荐指数
2
解决办法
3万
查看次数