Does this GetEnumAsStrings <T> () method invent the wheel?

I have a number of transfers and you need to get them as to list through them and therefore did . List<string>GetEnumAsStrings<T>()

But it seems to me that there will be an easier way.

Is there a built-in method for listing how this is in 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 to everyone, very insightful. Since I ended up needing this for Silverlight , which does not seem to have GetValues()or GetNames()for enumerations, I created 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;
}
+3
2

, LINQ:

var enums = Enum.GetNames(typeof(TestModes)).ToList();

, GetNames ... ToList().

Edit:
. , ToList :

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

. ? , , , . IEnumerable . (, ) .

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;
}
+8

MSDN - Enum.GetNames

, :

List<string> testModes = Enum.GetNames(typeof(TestModes)).ToList();

, .NET 2.0

List<string> testModes = new List<string>(Enum.GetNames(typeof(TestModes)));

List<string>, .

+7

Source: https://habr.com/ru/post/1749408/


All Articles