What to use besides enum for c#

后端 未结 3 1909
猫巷女王i
猫巷女王i 2021-02-06 00:04

So currently have an enumeration used on the status of an application. However, something feels off when using it against the ui. To many conversions between integer and string

3条回答
  •  野的像风
    2021-02-06 00:38

    My team had this issue in our recent project. We kept the enums, because they are the thing to use for a finite list of known constant values, but we did a few things to make them more developer-friendly:

    1. We decorated the enum values with [Description()] attributes containing the "friendly name" of each enum constant.
    2. We created a GetDescription() extension method that would reflectively examine the enum constant's Description attribute and return the friendly name. If it doesn't have one, the method attempts to insert spaces into the ToString() of the enum constant name. As CamelCased enum constants were a style requirement enforced by ReSharper, this worked for about 90% of our constants, and Description attributes handled the rest (mostly uppercase acronyms in the name).
    3. We created a ParseEnum() generic extension method for strings that basically wraps Enum.Parse() (which is oogly; requires specifying the Enum type in the method and then casting to it). I think it may be smart enough to try looking for description attributes first, or else we simply use the still-readable ToString() representation as the data value of the drop-down item.

    So, given the following:

    public enum MyItems
    {
       [Description("Item One")]
       ItemOne,
       [Description("Item Two")]
       ItemTwo,
       [Description("Item Three")]
       ItemThree
    }
    

    we could populate a DropDownList with user-friendly choices in two lines:

    foreach(MyValues value in Enum.GetValues())
       myDDL.Items.Add(New ListItem(value.GetDescription(), value.ToString())
    

    ... and then we could parse the selection back out with very readable code:

    var theValue = myDDL.SelectedItem.Value.ParseEnum()
    

    EDIT: I have been asked for the GetDescription() method. I'm a little iffy about sharing the whole thing, but here's the basic algorithm for getting a Description attribute that decorates an enum constant. Parsing a CamelCased name is pretty straightforward RegEx splits on capital letters, and our implementation's a little naive anyway. This snippet requires System.ComponentModel.DescriptionAttribute (which is also the decorator for the enum constants), and enumType is the "this" parameter of the extension method, of type Enum:

    var attr = enumType.GetType().GetField(enumType.ToString())
                     .GetCustomAttributes(typeof(DescriptionAttribute), false);
       if (attr.Length > 0)
          return ((DescriptionAttribute)attr[0]).Description;
    

提交回复
热议问题