Enum values in a list

2020-08-22 06:25发布

问题:

I've a enum class like,

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

in my business object I just declare this enum as

private List<USERTYPE> userType=new List<USERTYPE>;

and in the get/set method, I tried like

public List<USERTYPE> UserType
    {
        get 
        {
            return userType;
        }
        set
        { 
            userType= value; 
        }
    }

here it returns the no of rows as 0, how can I get all the values in the Enum here, can anyone help me here...

回答1:

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));
}


回答2:

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));


回答3:

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));


回答4:

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.



回答5:

UserTypeCan you please try with that,

 UserType = Enum.GetValues(typeof(USERTYPE)).OfType<USERTYPE>().ToList();


标签: c# asp.net