String representation of an Enum

后端 未结 30 2332
不思量自难忘°
不思量自难忘° 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:10

    Unfortunately reflection to get attributes on enums is quite slow:

    See this question: Anyone know a quick way to get to custom attributes on an enum value?

    The .ToString() is quite slow on enums too.

    You can write extension methods for enums though:

    public static string GetName( this MyEnum input ) {
        switch ( input ) {
            case MyEnum.WINDOWSAUTHENTICATION:
                return "Windows";
            //and so on
        }
    }
    

    This isn't great, but will be quick and not require the reflection for attributes or field name.


    C#6 Update

    If you can use C#6 then the new nameof operator works for enums, so nameof(MyEnum.WINDOWSAUTHENTICATION) will be converted to "WINDOWSAUTHENTICATION" at compile time, making it the quickest way to get enum names.

    Note that this will convert the explicit enum to an inlined constant, so it doesn't work for enums that you have in a variable. So:

    nameof(AuthenticationMethod.FORMS) == "FORMS"
    

    But...

    var myMethod = AuthenticationMethod.FORMS;
    nameof(myMethod) == "myMethod"
    

提交回复
热议问题