可以在枚举中添加一个空格或特殊字符的字符串 [英] Is it possible to add a string with spaces or specialcharacters to an enum

查看:415
本文介绍了可以在枚举中添加一个空格或特殊字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hii,



是否可以在枚举中添加一个空格或特殊字符的字符串



例如我有一个字符串,如保险KR用户(名称)我尝试将此字符串包含在枚举中,如

 code> public enum MemberGroup 
{
保险KR用户(名称)
}

但它捕捉错误。请给我一个解决方案,将这些类型的字符串包含在枚举中。

解决方案

枚举成员本身必须是有效标识符,因此它不能包含空格或特殊



但是,您可以使用 DescriptionAttribute 为每个枚举值提供更完整的描述:

  public enum MemberGroup 
{
[描述(保险KR用户(名称))]
要保存描述,请使用以下内容:

$($)



< b
$ b

  public static string GetDescription(枚举值)
{
FieldInfo fi = value.GetType()GetField(value.ToString ());
DescriptionAttribute [] attributes =
(DescriptionAttribute [])fi.GetCustomAttributes(
typeof(DescriptionAttribute),false);
return(attributes.Length> 0)?属性[0] .Description:value.ToString();
}


Hii,

Is it possible to add a string with spaces or specialcharacters to an enum

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.

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();
}

这篇关于可以在枚举中添加一个空格或特殊字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆