第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從描述屬性獲取Enum

從描述屬性獲取Enum

MM們 2019-07-10 10:22:33
從描述屬性獲取Enum我有一個泛型擴展方法,它獲取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;}所以我可以.。string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"現(xiàn)在,我試著在另一個方向上計算出等價的函數(shù),就像.Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
查看完整描述

3 回答

?
拉風的咖菲貓

TA貢獻1995條經(jīng)驗 獲得超2個贊

與其使用擴展方法,不如嘗試一些靜態(tài)方法。

public static class Utility{
    public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

    public static T GetEnumValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields                        .SelectMany(f => f.GetCustomAttributes(
                            typeof(DescriptionAttribute), false), (
                                f, a) => new { Field = f, Att = a })
                        .Where(a => ((DescriptionAttribute)a.Att)
                            .Description == description).SingleOrDefault();
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }}

在這里使用

var result1 = Utility.GetDescriptionFromEnumValue(
    Animal.GiantPanda);var result2 = Utility.GetEnumValueFromDescription<Animal>(
    "Lesser Spotted Anteater");


查看完整回答
反對 回復 2019-07-10
  • 3 回答
  • 0 關注
  • 639 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號