Skip to content

Instantly share code, notes, and snippets.

@panlw
Last active December 21, 2015 22:09
Show Gist options
  • Save panlw/6373364 to your computer and use it in GitHub Desktop.
Save panlw/6373364 to your computer and use it in GitHub Desktop.
List enum values
private static readonly string unknownEnumId = "unknown";
private static readonly Dictionary<Type, object> enumValuesCache =
new Dictionary<Type, object>();
/// <summary>
/// List all values anotated by XmlEnum
/// </summary>
/// <returns></returns>
public static List<XmlEnumValue<TEnum>> GetEnumValues<TEnum>() {
var t = typeof(TEnum);
if (enumValuesCache.ContainsKey(t)) {
return enumValuesCache[t] as List<XmlEnumValue<TEnum>>;
}
else {
var vals = new List<XmlEnumValue<TEnum>>();
var fs = t.GetFields();
var prefix = t.ToString().ToLower() + ".";
foreach (var f in fs) {
var attrs = f.GetCustomAttributes(typeof(
XmlEnumAttribute), false);
if (attrs != null && attrs.Length > 0) {
var id = (attrs[0] as XmlEnumAttribute).Name;
if (id != unknownEnumId) {
var val = new XmlEnumValue<TEnum>() {
Value = (TEnum)f.GetValue(null),
Id = id, Name = GetMessage(prefix + id)
};
vals.Add(val);
}
}
}
enumValuesCache.Add(t, vals);
return vals;
}
}
/// <summary>
/// Get message
/// </summary>
/// <param name="id">message id</param>
/// <returns></returns>
public static string GetMessage(string id) {
return i18n.GetMessageValue(id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment