Enum values in a list

前端 未结 5 1027
悲&欢浪女
悲&欢浪女 2021-02-20 11:38

I\'ve a enum class like,

public enum USERTYPE
{
   Permanant=1,
   Temporary=2,
}

in my business object I just declare this enum as

<         


        
相关标签:
5条回答
  • 2021-02-20 12:05

    If you want to get specific enum value from the list user.UserType then you first need to Add enum value to this list:

    var user = new User();
    //1 value - PERMANENT
    user.UserType.Add(USERTYPE.Permanent);
    

    But if you only need to get all the possible values from an arbitrary enum then you can try Enum.GetValues

    //2 values - Permanant and Temporary
    var enums = Enum.GetValues(typeof(USERTYPE));
    
    0 讨论(0)
  • 2021-02-20 12:07

    What you have is basically List of enum. Not individual items inside that enum.

    To get list of enum values you can do

    string[] str = Enum.GetNames(typeof(USERTYPE));
    

    To use in get/set return string[] instead of List<>

    public string[] UserType
    {
        get 
        {
            return Enum.GetNames(typeof(USERTYPE));
        }
    }
    

    I think set will not work here because you cannot add values in enum at runtime.

    0 讨论(0)
  • 2021-02-20 12:11

    UserTypeCan you please try with that,

     UserType = Enum.GetValues(typeof(USERTYPE)).OfType<USERTYPE>().ToList();
    
    0 讨论(0)
  • 2021-02-20 12:16

    You can use this to get all individual enum values:

    private List<USERTYPE> userTypes = Enum.GetValues(typeof(USERTYPE)).Cast<USERTYPE>().ToList();
    

    If you do things like this more often, you could create a generic utility method for it:

    public static T[] GetEnumValues<T>() where T : struct {
        if (!typeof(T).IsEnum) {
            throw new ArgumentException("GetValues<T> can only be called for types derived from System.Enum", "T");
        }
        return (T[])Enum.GetValues(typeof(T));
    }
    
    0 讨论(0)
  • 2021-02-20 12:31

    GetValues returns System.Array, but we know it's really a TEnum[] (that is a one-dimensional array indexed from zero) where TEnum is USERTYPE in your case. Therefore use:

    var allUsertypeValues = (USERTYPE[])Enum.GetValues(typeof(USERTYPE));
    
    0 讨论(0)
提交回复
热议问题