如何将以下Enum转换为字符串列表?将enum转换为列表<string>
[Flags]
public enum DataSourceTypes
{
None = 0,
Grid = 1,
ExcelFile = 2,
ODBC = 4
};
我找不到这个确切的问题,这Enum to List是最接近的,但我特别希望List<string>
如何将以下Enum转换为字符串列表?将enum转换为列表<string>
[Flags]
public enum DataSourceTypes
{
None = 0,
Grid = 1,
ExcelFile = 2,
ODBC = 4
};
我找不到这个确切的问题,这Enum to List是最接近的,但我特别希望List<string>
使用Enum
的静态方法,GetNames
。它返回一个string[]
,像这样:
Enum.GetNames(typeof(DataSourceTypes))
如果你想创建一个只做这只有一种类型的enum
,也该数组转换为List
的方法,你可以写这样的事情:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
我想补充另一种解决方案: 以我为例,我需要在下拉按钮列表项使用枚举组。因此,他们可能有空间,即对用户更友好的描述需要:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
在一个辅助类(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();
}
当你调用这个帮助你将得到清单项目描述。
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
此外: 在任何情况下,如果要实现这个方法,你需要: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();
*/
}
非常有用!谢谢;) – 2015-10-29 16:43:53
这涵盖了这个简单但非常受欢迎的问题的另一个方面,谢谢。 – 2017-09-20 08:36:06
你刚才问这个问题,你可以自己回答吗? – juharr 2013-02-20 03:14:25
您可以提出并回答您自己的问题。我担心的是,这是一个重复的问题无论如何 – 2013-02-20 03:16:34
应该是维基! – 2013-02-20 03:20:37