是否有可能为一个字符串用空格或specialcharacters添加到枚举 [英] Is it possible to add a string with spaces or specialcharacters to an enum
问题描述
许志国,
是否有可能一个字符串,用空格或specialcharacters添加到枚举
Is it possible to add a string with spaces or specialcharacters to an enum
有关,例如我喜欢的保险KR用户(名称)我试图包含这个字符串转换成枚举像
For e.g I have a string like "Insurance KR Users (Name)" i have tried to include this string into enum like
public enum MemberGroup
{
Insurance KR Users (Name)
}
但它捕获错误。请给我一个解决方案,包括这些类型的字符串转换为枚举。
but it catching errors. Please give me a solution to include these types of strings into enum.
推荐答案
在枚举成员本身必须是一个的有效的标识符,所以它不能包含空格或特殊字符。
The enum members itself must be a valid identifier, so it can't contain spaces or special characters.
但是你可以使用 DescriptionAttribute
为每个枚举值的更为完整的描述:
But you could use the DescriptionAttribute
to provide a more complete description of each enum value:
public enum MemberGroup
{
[Description("Insurance KR Users (Name)")]
InsuranceKrUsers_Name
}
要检索的描述,可以使用这样的:
To retrieve the description, use something like this:
public static string GetDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
这篇关于是否有可能为一个字符串用空格或specialcharacters添加到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!