我知道这是一个旧线程,但这里有一种稍微不同的方法,它使用枚举上的属性,然后使用辅助类来查找匹配的枚举。
这样,您可以在单个枚举上拥有多个映射。
public enum Age
{
[Metadata("Value", "New_Born")]
[Metadata("Value", "NewBorn")]
New_Born = 1,
[Metadata("Value", "Toddler")]
Toddler = 2,
[Metadata("Value", "Preschool")]
Preschool = 4,
[Metadata("Value", "Kindergarten")]
Kindergarten = 8
}
像我这样的助手类
public static class MetadataHelper
{
public static string GetFirstValueFromMetaDataAttribute<T>(this T value, string metaDataDescription)
{
return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
}
private static IEnumerable<string> GetValueFromMetaDataAttribute<T>(T value, string metaDataDescription)
{
var attribs =
value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (MetadataAttribute), true);
return attribs.Any()
? (from p in (MetadataAttribute[]) attribs
where p.Description.ToLower() == metaDataDescription.ToLower()
select p.MetaData).ToList()
: new List<string>();
}
public static List<T> GetEnumeratesByMetaData<T>(string metadataDescription, string value)
{
return
typeof (T).GetEnumValues().Cast<T>().Where(
enumerate =>
GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
p => p.ToLower() == value.ToLower())).ToList();
}
public static List<T> GetNotEnumeratesByMetaData<T>(string metadataDescription, string value)
{
return
typeof (T).GetEnumValues().Cast<T>().Where(
enumerate =>
GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
p => p.ToLower() != value.ToLower())).ToList();
}
}
然后你可以做类似的事情
var enumerates = MetadataHelper.GetEnumeratesByMetaData<Age>("Value", "New_Born");
为了完整起见,这里是属性:
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public class MetadataAttribute : Attribute
{
public MetadataAttribute(string description, string metaData = "")
{
Description = description;
MetaData = metaData;
}
public string Description { get; set; }
public string MetaData { get; set; }
}