這是一個小的可重複使用的解決方案。這是一個抽象類,它將從類型T中提取類型爲K的所有屬性。
abstract class AbstractAttributes<T, K>
{
protected List<K> Attributes = new List<K>();
public AbstractAttributes()
{
foreach (var member in typeof(T).GetMembers())
{
foreach (K attribute in member.GetCustomAttributes(typeof(K), true))
Attributes.Add(attribute);
}
}
}
如果我們現在要只提取屬性DescriptionAttribute
類型,我們可以使用下面的類。
class DescriptionAttributes<T> : AbstractAttributes<T, DescriptionAttribute>
{
public List<string> Descriptions { get; set; }
public DescriptionAttributes()
{
Descriptions = Attributes.Select(x => x.Description).ToList();
}
}
該類將從類型T
提取DescriptionAttribute
類型的唯一的屬性。但要真正在你的情境中使用這個類,你只需要做以下事情。
new DescriptionAttributes<ContractorType>().Descriptions.ForEach(x => Console.WriteLine(x));
這行代碼會寫出來,你作爲你的DescriptionAttribute
類型的屬性參數的所有描述。如果需要提取一些其他屬性,只需創建一個從AbstractAttributes<T, K>
類派生的新類,並使用適當的屬性關閉其類型K
。
由於這(顯然)是一個flags-enum,因此您的「收件人/傳遞」實際上不應該是valu e 3?像,不應該是'ContractorType.RECIPIENT |的組合ContractorType.DELIVER'?否則'(ContractorType.RECIPIENT | ContractorType.DELIVER)!= ContractorType.RECIPIENT_DELIVER'。也許你應該刪除'[Flags]'屬性。 –