获取枚举*子集*的描述属性



我知道如何获得每个枚举的描述。我正试图弄清楚如何获得子集

以下是我所拥有的,我相信这表明了我的目标:

public enum ModelType : int
{
/// <summary>
/// No model type. For internal use only.
/// </summary>
[Description("NA")]
_NA = 0,  
[Description("Literal Model")]
Literal = 1,
[Description("Linear Model")]
Linear = 2,
[Description("Curve Model")]
Curve = 3
}

var values = Enum.GetValues(typeof(ModelType))
.Cast<ModelType>()
.Where(x => x > ModelType._NA)  // filter
.ToArray();
var attributes = values.GetMembers() // this is wrong
.SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
.ToList();
return attributes.Select(x => x.Description);

这应该有效:

var type = typeof(ModelType);
var propNames = Enum.GetValues(type)
.Cast<ModelType>()
.Where(x => x > ModelType._NA)  // filter
.Select(x => x.ToString())
.ToArray();
var attributes = propNames
.Select(n => type.GetMember(n).First())
.SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
.ToList();
return attributes.Select(x => x.Description);

最新更新