Home >Backend Development >C++ >How to Get String Representation of Enum Values in C#?
Consider the following enumeration:
public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 }
However, you require the string "FORMS" when requesting AuthenticationMethod.FORMS, not the ID of 1.
The "StringValue" custom attribute can address this issue:
public class StringValue : System.Attribute { private readonly string _value; public StringValue(string value) { _value = value; } public string Value { get { return _value; } } }
Then, you can apply this attribute to your enumeration:
public enum AuthenticationMethod { [StringValue("FORMS")] FORMS = 1, [StringValue("WINDOWS")] WINDOWSAUTHENTICATION = 2, [StringValue("SSO")] SINGLESIGNON = 3 }
To retrieve this StringValue, you'll need the following:
public static class StringEnum { public static string GetStringValue(Enum value) { string output = null; Type type = value.GetType(); // Look for our 'StringValueAttribute' in the field's custom attributes FieldInfo fi = type.GetField(value.ToString()); StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[]; if (attrs.Length > 0) { output = attrs[0].Value; } return output; } }
This solution allows you to obtain the string value for enumerations like this:
string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
However, a better solution is the type-safe-enum pattern:
public sealed class AuthenticationMethod { private readonly String name; private readonly int value; public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS"); public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS"); public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN"); private AuthenticationMethod(int value, String name){ this.name = name; this.value = value; } public override String ToString(){ return name; } }
For explicit (or implicit) type conversion, add a static field with mapping, fill the mapping in the instance constructor, and add a user-defined type conversion operator:
private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();<br>instance[name] = this;<br>public static explicit operator AuthenticationMethod(string str)<br>{</p> <pre class="brush:php;toolbar:false">AuthenticationMethod result; if (instance.TryGetValue(str, out result)) return result; else throw new InvalidCastException();
}
The above is the detailed content of How to Get String Representation of Enum Values in C#?. For more information, please follow other related articles on the PHP Chinese website!