是否可以在枚举中添加带空格或特殊字符的字符串? [英] Is it possible to add a string with spaces or special characters to an enum?

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

问题描述

是否可以在枚举中添加包含空格或特殊字符的字符串?

Is it possible to add a string with spaces or special characters to an enum?

例如,我有一个字符串 Insurance KR Users (名称),我试图将此字符串包含在枚举中:

For example, I have a string Insurance KR Users (Name), I have tried to include this string into an enum:

    public enum MemberGroup
    {
        Insurance KR Users (Name)
    }

但引发错误。

如何将这些类型的字符串包含在枚举中?

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

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

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