Name Enum 有名字,Name4 是一个没有类别属性的成员示例
public enum Name
{
[Category(Category.Category1)]
Name1,
[Category(Category.Category2)]
Name2,
[Category(Category.Category3)]
Name3,
Name4
}
public enum Category
{
//default value to return from GetCategory if no Category is assigned
None,
Category1,
Category2,
Category3
}
public class CategoryAttribute : Attribute
{
public Category Category { get; set; }
public CategoryAttribute(Category cat)
{
Category = cat;
}
}
e 参数中传递的值是枚举的底层类型的值,在本例中为 int。为了获取分配的属性,我们首先需要获取与 int 关联的名称,然后使用该名称搜索属性。
public static class NameMethods
{
public static Category GetCategory(this Name e)
{
var name = Enum.GetName(typeof(Name), e);
var member = e.GetType().GetMember(name).FirstOrDefault();
var attr = Attribute.GetCustomAttribute(member, typeof(CategoryAttribute)) as CategoryAttribute;
return attr?.Category ?? Category.None;
}
}
使用四种不同的类别运行代码
public static class Program
{
static void Main(string[] args)
{
var result = Name.Name1.GetCategory(); //Category1
var result1 = Name.Name2.GetCategory(); //Category2
var result2 = Name.Name3.GetCategory(); //Category3
var result3 = Name.Name4.GetCategory(); //None
}
}
如果您想反其道而行之,获取已分配给特定类别的名称列表,则可以使用此方法。请注意,此代码只允许为每个名称分配一个类别。
public static List<Name> GetNames(Category category)
{
//Find all Members of Name Enum Type that have a categoryAttribute with the Category property assigned to the category parameter.
var members = typeof(Name).GetMembers().ToList();
var result = new List<Name>();
foreach (var member in members)
{
//get attributes for member
var categoryAttribute = Attribute.GetCustomAttribute(member, typeof(CategoryAttribute)) as CategoryAttribute;
if (categoryAttribute != null && categoryAttribute.Category == category)
{
//use the member name to get an instance of enumerated type.
Enum.TryParse(member.Name, out Name name);
result.Add(name);
}
}
return result;
}