String representation of an Enum

后端 未结 30 2311
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

I have the following enumeration:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

T

30条回答
  •  萌比男神i
    2020-11-22 03:16

    When I'm confronted with this problem, there are a couple of questions that I try to find the answers to first:

    • Are the names of my enum values sufficiently friendly for the purpose, or do I need to provide friendlier ones?
    • Do I need to round-trip? That is, will I need to take text values and parse them into enum values?
    • Is this something I need to do for many enums in my project, or just one?
    • What kind of UI elements will I be presenting this information in - in particular, will I be binding to the UI, or using property sheets?
    • Does this need to be localizable?

    The simplest way to do this is with Enum.GetValue (and support round-tripping using Enum.Parse). It's also often worth building a TypeConverter, as Steve Mitcham suggests, to support UI binding. (It's not necessary to build a TypeConverter when you're using property sheets, which is one of the nice things about property sheets. Though lord knows they have their own issues.)

    In general, if the answers to the above questions suggest that's not going to work, my next step is to create and populate a static Dictionary, or possibly a Dictionary>. I tend to skip the intermediate decorate-the-code-with-attributes step because what's usually coming down the pike next is the need to change the friendly values after deployment (often, but not always, because of localization).

提交回复
热议问题