28

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

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

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

4

3 回答 3

48

不,这是不可能的,但您可以将属性附加到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
}

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

于 2013-03-17T06:45:12.043 回答
5

这很简单。为您的字符串创建一个扩展方法,该方法根据您的编码约定返回一个格式化的字符串。您可以在很多地方使用它,而不仅仅是在这里。这适用于 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;
    }
于 2013-03-17T06:46:58.000 回答
1
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
}          

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

于 2013-03-17T07:19:04.210 回答