如何从枚举指定的字符串值 [英] how to get assigned string values from enum

查看:144
本文介绍了如何从枚举指定的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了这个枚举

 public enum Days
    {
        [Display("Monday")]
        Mon,
        [Display("Tuesday")]
        Tue,
        [Display("Wednesday")]
        Wed,
        [Display("Thursday")]
        Thu,
        [Display("Friday")]
        Fri,
        [Display("Satrday")]
        Sat,
    }

我想要得到的字符串星期一。我试图这样做。

I want to get the string "Monday". I tried by doing this

Console.WriteLine(Days.mon);



不过是给了我问而不是星期一。
有没有什么办法让字符串周一

But is gives me "mon" instead of "Monday". is there any way to get string Monday?

推荐答案

我提高的this回答给你一个更全面的圆形出解决方案,具有较好的语义语法。

I've enhanced this answer to give you a more fully rounded-out solution, with better semantic syntax.

using System;
using System.ComponentModel;

public static class EnumExtensions {

    // This extension method is broken out so you can use a similar pattern with 
    // other MetaData elements in the future. This is your base method for each.
    public static T GetAttribute<T>(this Enum value) where T : Attribute {
        var type = value.GetType();
        var memberInfo = type.GetMember(value.ToString());
        var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
        return (T)attributes[0];
    }

    // This method creates a specific call to the above method, requesting the
    // Description MetaData attribute.
    public static string ToName(this Enum value) {
        var attribute = value.GetAttribute<DescriptionAttribute>();
        return attribute == null ? value.ToString() : attribute.Description;
    }

}

这解决方案创建一对延伸在枚举的方法,让你做你在寻找什么。我已经增进了你的枚举代码略,用于 DisplayAttribute 的语法。System.ComponentModel.DataAnnotations

This solution creates a pair of extension methods on Enum, to allow you to do what you're looking for. I've enhanced your Enum code slightly, to use the syntax for the DisplayAttribute class of System.ComponentModel.DataAnnotations.

using System.ComponentModel.DataAnnotations;

    public enum Days {
        [Display(Name = "Sunday")]
        Sun,
        [Display(Name = "Monday")]
        Mon,
        [Display(Name = "Tuesday")]
        Tue,
        [Display(Name = "Wednesday")]
        Wed,
        [Display(Name = "Thursday")]
        Thu,
        [Display(Name = "Friday")]
        Fri,
        [Display(Name = "Saturday")]
        Sat
    }

要使用上述扩展方法,你现在只需调用以下几点:

To use the above extension method, you would now simply call the following:

Console.WriteLine(Days.Mon.ToName());

var day = Days.Mon;
Console.WriteLine(day.ToName());

这篇关于如何从枚举指定的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆