我们有一个枚举如何在列表中获取枚举及其值? [英] We have a enums how we get enums and its values in a list ?

查看:251
本文介绍了我们有一个枚举如何在列表中获取枚举及其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public enum AccountCategory
   {
       [EnumMember]
       System_Owner = 2,
       [EnumMember]
       System_Account = 3,
       [EnumMember]
       Customer = 4,
       [EnumMember]
       Supplier = 5
   }







public enum MainFeatures
    {
        /// <summary>
        /// No attribute set
        /// </summary>
        [EnumMember]
        NotSet = 0,
        /// <summary>
        /// Owner reference
        /// </summary>
        [EnumMember]
        Owner_Reference = 1,



}



我拥有什么试过:



i只在代码下方尝试获取枚举列表

var value = enums.tolist();


}

What I have tried:

i tried only below code to get the list of enums
var value=enums.tolist();

推荐答案

你的代码赞:

Your code Like :
var value=Enum.GetValues(typeof(YourEnum)).Cast<yourenum>().ToList(); 


查看枚举参考



have a look on this for Enum reference

enum EnumRank
       {
           First=1,
           Second=2,
           Third=3

       }
       static void Main(string[] args)
       {
           //To Get the list of enum Values
           List<int> Numbers = Enum.GetValues(typeof(EnumRank)).Cast<int>().ToList();  // 1,2 3

           //To Get the List of Enum Names
           List<string> Names = Enum.GetNames(typeof(EnumRank)).ToList();  //First, Second, Third

           // Cast Enum to a string
           EnumRank value = EnumRank.First;
           string name = Enum.GetName(typeof(EnumRank), value); // First

           // Cast a string value to Enum Object
           string enumInString = "Third";
           EnumRank enumValue = (EnumRank)Enum.Parse(typeof(EnumRank), enumInString); // Third Enum

       }


解决方案1和2不完整。当一些枚举成员具有相同的整数值(通常需要)时,麻烦就开始了。无论如何,这些接近都没有给你定义它们的枚举类型成员。



有关详细说明和全面的解决方案,请参阅我的文章: 枚举类型不枚举!解决.NET和语言限制



有关其他功能,请参阅枚举系列的另外三篇文章,参考简介部分。



-SA
Solutions 1 and 2 are incomplete. The trouble starts when some enumeration members have the same integer value (which is often needed). Anyway, these approached don't give you enumeration type members as you define them.

For the detailed explanations and a comprehensive solution, please see my article: Enumeration Types do not Enumerate! Working around .NET and Language Limitations.

For additional features, please see three more articles of my enumeration series, referenced in the "Introduction" section.

—SA


这篇关于我们有一个枚举如何在列表中获取枚举及其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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