字符串表示的字符串表示,请考虑以下枚举:
public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 },但是,请求AutheThicationMethod时,您需要字符串“表单”。表单,而不是1的ID。 >
要检索此字符串value,您将需要以下内容:
public class StringValue : System.Attribute { private readonly string _value; public StringValue(string value) { _value = value; } public string Value { get { return _value; } } }
>此解决方案允许您获取这样的枚举的字符串值:
public enum AuthenticationMethod { [StringValue("FORMS")] FORMS = 1, [StringValue("WINDOWS")] WINDOWSAUTHENTICATION = 2, [StringValue("SSO")] SINGLESIGNON = 3 }
,但是,一个更好的解决方案是类型安全性 - 元素模式:
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; } }>
string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
用于显式(或隐式)类型转换,添加带有映射的静态字段,填充映射在实例构造函数中,然后添加一个用户 - 定义的类型转换运算符:
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; } }
instance [name] = this;
> public static expatic equipit Operator authenticationMethod(String str)以上是如何在C#中获取枚举值的字符串表示形式?的详细内容。更多信息请关注PHP中文网其他相关文章!