C# 如何使用带空格的枚举值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15458257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:54:19  来源:igfitidea点击:

How to have enum values with spaces?

c#.netvb.netenums

提问by CJ7

How can I achieve the following using enums in .NET? I would like to have descriptions for each value that include spaces.

如何使用枚举实现以下目标.NET?我想对每个包含空格的值进行描述。

public enum PersonGender
    {
        Unknown = 0,
        Male = 1,
        Female = 2,
        Intersex = 3,
        Indeterminate = 3,
        Non Stated = 9,
        Inadequately Described = 9
    }

I would like to be able to choose whether to use either the description or integer each time I use a value of this type.

我希望能够在每次使用这种类型的值时选择是使用描述还是整数。

回答by p.s.w.g

No that's not possible, but you can attach attributes to enummembers. The EnumMemberAttributeis designed exactly for the purpose you described.

不,这是不可能的,但您可以将属性附加到enum成员。该EnumMemberAttribute恰好专为您所描述的目的。

public enum PersonGender
{
    Unknown = 0,
    Male = 1,
    Female = 2,
    Intersex = 3,
    Indeterminate = 3,

    [EnumMember(Value = "Not Stated")]
    NonStated = 9,

    [EnumMember(Value = "Inadequately Described")]
    InadequatelyDescribed = 9
}

For more information on how to use the EnumMemberAttributeto convert strings to enumvalues, see this thread.

有关如何使用EnumMemberAttribute将字符串转换为enum值的更多信息,请参阅此线程

回答by theMayer

This is easy. Create an extension method for your string that returns a formatted string based on your coding convention. You can use it in lots of places, not just here. This one works for camelCase and TitleCase.

这很简单。为您的字符串创建一个扩展方法,该方法根据您的编码约定返回一个格式化的字符串。您可以在很多地方使用它,而不仅仅是在这里。这个适用于camelCase 和TitleCase。

    public static String ToLabelFormat(this String s)
    {
        var newStr = Regex.Replace(s, "(?<=[A-Z])(?=[A-Z][a-z])", " ");
        newStr = Regex.Replace(newStr, "(?<=[^A-Z])(?=[A-Z])", " ");
        newStr = Regex.Replace(newStr, "(?<=[A-Za-z])(?=[^A-Za-z])", " ");

        return newStr;
    }

回答by Mohsen Heydari

var assembly = Assembly.LoadFrom("ResourcesLib.DLL");            
var resourceManager =
new ResourceManager("ResourcesLib.EnumDescriptions", assembly);                        

var lst = Enum.GetValues(typeof(PersonGender)).Cast<PersonGender>().ToList();
foreach (var gender in lst)
{
  Console.WriteLine(gender); // Name
  Console.WriteLine((int)gender); //Int Value
  Console.WriteLine(resourceManager.GetString(gender.ToString()));//localized Resorce
}          

So spaces may reside in localized resource ...

所以空间可能驻留在本地化资源中......