2
我已按位枚举具有多个值,每个值都具有description属性。如何获得按位枚举的属性
[Flags]
public enum ParkingAreaType
{
[Description("Car Park")]
CarPark = 1,
[Description("Residential Permit")]
ResidentialPermitZone = 2,
[Description("Commercial Permit")]
CommercialPermitZone = 4,
[Description("On Street Parking")]
OnStreetParking = 8,
Any =
CarPark | ResidentialPermitZone | CommercialPermitZone
}
我已经使用并试图多个扩展方法,我就非常相似,这
Getting attributes of Enum's value
其他一些问题,发现How to get attributes of enum
即时通讯目前使用的代码中的这段来自John Skeets EnumInternals https://github.com/jskeet/unconstrained-melody/blob/master/UnconstrainedMelody/EnumInternals.cs
private static string GetDescription(T value)
{
FieldInfo field = typeof(T).GetField(value.ToString());
return field.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.Select(x => x.Description)
.FirstOrDefault();
}
上面的代码将工作,如果我只传入一个枚举,但如果我传入按位枚举它将抛出一个对象引用。我已经从不同的例子中尝试了以上几种不同的变体,但都具有相同的结果。
我只是无法弄清楚如何让被传入的说明列表。
干杯谢谢,spot on – InitLipton