C# 将枚举转换为 List<string>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14971631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an enum to List<string>
提问by Jeremy Thompson
How do I convert the following Enum to a List of strings?
如何将以下枚举转换为字符串列表?
[Flags]
public enum DataSourceTypes
{
None = 0,
Grid = 1,
ExcelFile = 2,
ODBC = 4
};
I couldn't find this exact question, this Enum to Listis the closest but I specifically want List<string>
我找不到这个确切的问题,这个Enum to List是最接近的,但我特别想要List<string>
采纳答案by Jeremy Thompson
Use Enum
's static method, GetNames
. It returns a string[]
, like so:
使用Enum
的静态方法,GetNames
. 它返回 a string[]
,如下所示:
Enum.GetNames(typeof(DataSourceTypes))
If you want to create a method that does only this for only one type of enum
, and also converts that array to a List
, you can write something like this:
如果您想创建一个仅对一种类型执行此操作enum
并将该数组转换为 a 的方法List
,您可以编写如下内容:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
You will need Using System.Linq;
at the top of your class to use .ToList()
您将需要Using System.Linq;
在课程顶部使用 .ToList()
回答by rkmorgan
I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:
我想添加另一个解决方案:就我而言,我需要在下拉按钮列表项中使用 Enum 组。所以他们可能有空间,即需要更多用户友好的描述:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
In a helper class (HelperMethods) I created the following method:
在辅助类 (HelperMethods) 中,我创建了以下方法:
public static List<string> GetListOfDescription<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
}
When you call this helper you will get the list of item descriptions.
当您调用此助手时,您将获得项目描述列表。
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.
附加:无论如何,如果你想实现这个方法,你需要枚举的 :GetDescription 扩展。这就是我使用的。
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
/* how to use
MyEnum x = MyEnum.NeedMoreCoffee;
string description = x.GetDescription();
*/
}