【发布时间】:2013-05-28 23:39:24
【问题描述】:
所以我需要从我的enum 获得一个List<string>
这是我到目前为止所做的:
枚举定义
[Flags]
public enum ContractorType
{
[Description("Recipient")]
RECIPIENT = 1,
[Description("Deliver")]
DELIVER = 2,
[Description("Recipient / Deliver")]
RECIPIENT_DELIVER = 4
}
HelperClass 及其方法可以满足我的需要:
public static class EnumUtils
{
public static IEnumerable<string> GetDescrptions(Type enumerator)
{
FieldInfo[] fi = enumerator.GetFields();
List<DescriptionAttribute> attributes = new List<DescriptionAttribute>();
foreach (var i in fi)
{
try
{
yield return attributes.Add(((DescriptionAttribute[])i.GetCustomAttributes(
typeof(DescriptionAttribute),
false))[0]);
}
catch { }
}
return new List<string>{"empty"};
}
}
现在在我 yield 值的行中,我得到了一个 NullReferenceException。我错过了什么?语法对我来说看起来不错,但也许我忽略了一些东西?
编辑: 我在这里使用 .net Framework 4.0。
【问题讨论】:
-
既然这(显然)是一个标志枚举,那么您的“收件人/交付”实际上不应该是值 3 吗?比如,不应该是
ContractorType.RECIPIENT | ContractorType.DELIVER的组合吗?否则(ContractorType.RECIPIENT | ContractorType.DELIVER) != ContractorType.RECIPIENT_DELIVER。也许您应该删除[Flags]属性。
标签: c# reflection enums ienumerable custom-attributes