如何将以下枚举类型转换为字符串列表?
[Flags]
public enum DataSourceTypes
{
None = 0,
Grid = 1,
ExcelFile = 2,
ODBC = 4
};
我找不到这个确切的问题,这个Enum to List最接近,但我特别想要List<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();
}
Using System.Linq;
来使用.ToList()。
string enumItemAsString = nameof(DataSourceTypes.Grid)
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
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();
*/
}
[Description()]
,而是使用[EnumMember(Value =)]
,它可以自动反序列化JSON枚举! 它很容易实现,将x => x.GetDescription()
更改为x => x.GetAttributeOfType <EnumMemberAttribute>()。 Value
并更改方法:public static T GetAttributeOfType <T>(this Enum enumVal)where T:System.Attribute {var type = enumVal.GetType(); var memInfo = type.GetMember(enumVal.ToString()); var attributes = memInfo [0] .GetCustomAttributes(typeof(T),false); return(attributes.Length> 0)?(T)attributes [0]:null; }
- Jeremy Thompsonattr
为空(即值上没有描述属性),则GetDescription
扩展应返回field.Name
。 - Dazpublic class Enum<T> where T : struct, IConvertible
{
public static List<SelectItem> ToSelectItems
{
get
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
var values = Enum.GetNames(typeof(T));
return values.Select((t, i) => new SelectItem() {Id = i, Name = t}).ToList();
}
}
}
Enum.GetNames(typeof(DataSourceTypes))
返回的是一个通用的System.Array
,而不是一个字符串数组? - sookiepublic static string[] GetNames
。 - Jeremy Thompson