Is this GetEnumAsStrings<T>() method reinventing the wheel?
I have a number of enums and need to get them as List<string>
objects in order to enumerate through them and hence made the GetEnumAsStrings<T>()
method.
But it seems to me there would be an easier way.
Is there not a built-in method to get an enum like this into a List<string>
?
using System;
using System.Collections.Generic;
namespace TestEnumForeach2312
{
class Program
{
static void Main(string[] args)
{
List<string> testModes = StringHelpers.GetEnumAsStrings<TestModes>();
testModes.ForEach(s => Console.WriteLine(s));
Console.ReadLine();
}
}
public static class StringHelpers
{
public static List<string> GetEnumAsStrings<T>()
{
List<string> enumNames = new List<string>();
foreach (T item in Enum.GetValues(typeof(TestModes)))
{
enumNames.Add(item.ToString());
}
return enumNames;
}
}
public enum TestModes
{
Test,
Show,
Wait,
Stop
}
}
Addendum:
开发者_开发技巧Thanks everyone, very insightful. Since I ultimately needed this for Silverlight which doesn't seem to have GetValues()
or GetNames()
for enums, I made this method which I created from this method:
public static List<string> ConvertEnumToListOfStrings<T>()
{
Type enumType = typeof(T);
List<string> strings = new List<string>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
strings.Add(((T)value).ToString());
}
return strings;
}
You could do it as a one-liner using LINQ:
var enums = Enum.GetNames(typeof(TestModes)).ToList();
Now, keep in mind that GetNames
returns an array of strings... so you might not even need ToList()
.
Edit:
There are ways to improve on your edited code. Here's a simple one that uses ToList
rather than explicitly instantiating the list:
public static List<string> ConvertEnumToListOfStrings<T>()
{
Type enumType = typeof(T);
var fields = from field in enumType.GetFields()
where field.IsLiteral
select ((T)field.GetValue(enumType)).ToString();
return fields.ToList();
}
And this next one is my personal preference. Why instantiate a list at all? You probably just need to iterate over the names, not add or remove them from a list. So just use IEnumerable
and don't bother building the list at all. Saves you one (admittedly small) iteration and the memory overhead of another object.
public static IEnumerable<string> GetEnumNames<T>()
{
Type enumType = typeof(T);
var fields = from field in enumType.GetFields()
where field.IsLiteral
select ((T)field.GetValue(enumType)).ToString();
return fields;
}
MSDN - Enum.GetNames
So for your example it would be:
List<string> testModes = Enum.GetNames(typeof(TestModes)).ToList();
Or, if you're still back in .NET 2.0
List<string> testModes = new List<string>(Enum.GetNames(typeof(TestModes)));
If you really need it as a List<string>
, otherwise I would just work directly with the array.
精彩评论