String representation of an Enum

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

    If I'm understanding you correctly, you can simply use .ToString() to retrieve the name of the enum from the value (Assuming it's already cast as the Enum); If you had the naked int (lets say from a database or something) you can first cast it to the enum. Both methods below will get you the enum name.

    AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
    Console.WriteLine(myCurrentSetting); // Prints: FORMS
    string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
    Console.WriteLine(name); // Prints: FORMS
    

    Keep in mind though, the second technique assumes you are using ints and your index is 1 based (not 0 based). The function GetNames also is quite heavy by comparison, you are generating a whole array each time it's called. As you can see in the first technique, .ToString() is actually called implicitly. Both of these are already mentioned in the answers of course, I'm just trying to clarify the differences between them.

提交回复
热议问题