public class StringValue : System.Attribute { private readonly string _value; public StringValue(string value) { _value = value; } public string Value { get { return _value; } } }
public static class StringEnum { public static string GetStringValue(Enum value) { string output = null; Type type = value.GetType(); FieldInfo fi = type.GetField(value.ToString()); StringValue[] attrs = fi.GetCustomAttributes(typeof (StringValue), false) as StringValue[]; if (attrs != null && attrs.Length > 0) { output = attrs[0].Value; } return output; } }
private enum SignMagnitude { [StringValue("Negative")] Negative = -1, }
使用方法:
StringEnum.GetStringValue(SignMagnitude.Negative);