以下是一些可以提供帮助的实用程序扩展方法:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~
用法:
var listOfValues = typeof (A).ToList();
var listOfKeyValuePairs = typeof(A).ToListOfKeyValuePair();
var dictionaryOfValues = typeof(A).ToDictionary();
给定以下枚举:
public enum A
{
[EnumValueDescription("This is a")] a = 1,
[EnumValueDescription("This is b")] b = 2,
[EnumValueDescription("This is c")] c = 3,
[EnumValueDescription("This is d")] d = 4
};
以及以下自定义属性:
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = false)]
public class EnumValueDescriptionAttribute : Attribute
{
public string StringValue
{
get;
protected set;
}
public EnumValueDescriptionAttribute(string value)
{
this.StringValue = value;
}
}
以及以下扩展方法:
public static class EnumExtentions
{
public static List<Enum> ToList(this Type type)
{
return Enum.GetValues(type)
.OfType<Enum>()
.ToList();
}
public static Dictionary<int, string> ToDictionary(this Type type)
{
return type.GetEnumValues().Cast<Enum>().ToDictionary(Convert.ToInt32, e => e.GetDescription());
}
public static List<KeyValuePair<int, string>> ToListOfKeyValuePair(this Type type)
{
return Enum.GetValues(type)
.OfType<Enum>()
.Select(e => new KeyValuePair<int, string>(Convert.ToInt32(e), e.GetDescription()))
.ToList();
}
public static string GetDescription(this Enum value)
{
return value.GetDescription(null);
}
public static string GetDescription(this Enum value, string defaultValue)
{
var allFields = value.GetType().GetFields();
if (!allFields.Any())
return defaultValue;
var targetField = allFields.FirstOrDefault(fi => (fi.IsLiteral && (fi.GetValue(null).Equals(value))));
if (targetField == null)
return defaultValue;
var attrib = targetField.GetCustomAttributes(typeof(EnumValueDescriptionAttribute), false)
.OfType<EnumValueDescriptionAttribute>()
.FirstOrDefault();
return attrib == null ? defaultValue : attrib.StringValue;
}
}
目前尚不完全清楚您需要哪些其他操作方法。