C# Explicit Type Casting Enumeration
-
18-06-2021 - |
سؤال
I need to create a List of object of whatever Enumeration type is passed into the function below. I don't know what type it will be, but it can be any one of many possible enumerations in my project.
public static List<object> CreateEnumList(Enum enumeration)
{
List<object> returnList = new List<object>();
for (int enumIndex = 0; enumIndex < Enum.GetNames(enumeration.GetType()).Length; enumIndex++)
returnList.Add((enumeration.GetType())enumIndex);
return returnList;
}
How can I get the type cast to work correctly? The return value MUST be List of objects. Thank you
المحلول
This is enough
public static List<object> CreateEnumList(Enum enumeration)
{
return Enum.GetValues(enumeration.GetType()).Cast<object>().ToList();
}
نصائح أخرى
Solution 1
Generic Enum to List converter (C#) One for the utility library...
It takes an enum type and returns a generic list populated with each enum item.
public static List<T> EnumToList<T>()
{
Type enumType = typeof (T);
// Can't use type constraints on value types, so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray) {
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
Solution 2
This will return an IEnumerable<SomeEnum>
of all the values of an Enum.
Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
If you want that to be a List<SomeEnum>
, just add .ToList()
after .Cast<SomeEnum>()
.
public static List<T> CreateEnumList<T>(Enum enumeration)
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
Check here : How do I convert an enum to a list in C#?
Enum.Parse
will do exactly what you need:
returnList.Add(Enum.Parse(enumeration.GetType(), enumIndex.ToString()));
For example, this prints b
:
enum myEnum { a, b, c }
static void Main(string[] args)
{
var e = Enum.Parse(typeof(myEnum), "1");
Console.WriteLine(e);
}
How about
public IList<object> GetBoxedEnumValues<TEnum>()
{
Type enumType = typeOf(TEnum);
if (!enumType.IsEnum)
{
throw new NotSupportedException(
string.Format("\"{0}\" is not an Enum", enumType.Name));
}
return Enum.GetValues(enumType).Cast<object>().ToList();
}