[英]Compare Flag Enums by Description
我有以下枚舉:
[Flags]
public enum UserRoles {
[Description("Gestor")]
Admin = 1 << 0,
[Description("Editor")]
Editor = 1 << 1,
[Description("Membro")]
Member = 1 << 2
}
然后我有:
String[] currentUserRoles = new String[] { "Gestor, "Membro" }
UserRoles testRoles = UserRoles.Admin | UserRoles.Editor;
我想測試currentUserRoles中是否包含任何testRoles。
問題在於currentUserRoles是Description屬性。
我能夠使用解決
UserRoles role;
currentUserRoles.Select(x => x.Value).Any(y => (Enum.TryParse(y, true, out role) && testRoles.HasFlag(role)));
但是我想使用Description屬性進行比較。
我怎樣才能做到這一點?
謝謝
var result =
Enum.GetValues(typeof(UserRoles))
.Cast<UserRoles>()
.Where(r => (r & testRoles) == r)
.Select(r => typeof(UserRoles).GetField(r.ToString())
.GetCustomAttribute<DescriptionAttribute>()
.Description)
.Intersect(currentUserRoles)
.Any();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.