String representation of an Enum

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

I have the following enumeration:

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

T

30条回答
  •  梦谈多话
    2020-11-22 03:28

    If you think about the problem we're trying to solve, it's not an enum we need at all. We need an object that allows a certain number of values to be associated with eachother; in other words, to define a class.

    Jakub Šturc's type-safe enum pattern is the best option I see here.

    Look at it:

    • It has a private constructor so only the class itself can define the allowed values.
    • It is a sealed class so values can't be modifed through inheritence.
    • It is type-safe, allowing your methods to require only that type.
    • There is no reflection performance hit incurred by accessing the values.
    • And lastly, it can be modified to associate more than two fields together, for example a Name, Description, and a numeric Value.

提交回复
热议问题