Jer*_*son 88 .net c# enums generic-list
如何将以下枚举转换为字符串列表?
[Flags]
public enum DataSourceTypes
{
None = 0,
Grid = 1,
ExcelFile = 2,
ODBC = 4
};
Run Code Online (Sandbox Code Playgroud)
我找不到这个确切的问题,这个Enum to List是最接近但我特别想要的List<string>
Jer*_*son 159
使用Enum静态方法GetNames.它返回一个string[],如下:
Enum.GetNames(typeof(DataSourceTypes))
Run Code Online (Sandbox Code Playgroud)
如果你想创建一个只对一种类型只做一次的方法enum,并且还将该数组转换为a List,你可以这样写:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
Run Code Online (Sandbox Code Playgroud)
rkm*_*gan 28
我想添加另一个解决方案:在我的情况下,我需要在下拉按钮列表项中使用枚举组.所以他们可能有空间,即需要更多用户友好的描述:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
Run Code Online (Sandbox Code Playgroud)
在帮助器类(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();
}
Run Code Online (Sandbox Code Playgroud)
当您调用此帮助程序时,您将获得项目描述列表.
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
Run Code Online (Sandbox Code Playgroud)
附加:在任何情况下,如果要实现此方法,您需要:枚举的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();
*/
}
Run Code Online (Sandbox Code Playgroud)