[英]Compare Flag Enums by Description
I have the following enum: 我有以下枚举:
[Flags]
public enum UserRoles {
[Description("Gestor")]
Admin = 1 << 0,
[Description("Editor")]
Editor = 1 << 1,
[Description("Membro")]
Member = 1 << 2
}
And then I have: 然后我有:
String[] currentUserRoles = new String[] { "Gestor, "Membro" }
UserRoles testRoles = UserRoles.Admin | UserRoles.Editor;
I would like to test if any of the testRoles are included in currentUserRoles. 我想测试currentUserRoles中是否包含任何testRoles。
The problem is that currentUserRoles are the Description attribute. 问题在于currentUserRoles是Description属性。
I was able to solve this using 我能够使用解决
UserRoles role;
currentUserRoles.Select(x => x.Value).Any(y => (Enum.TryParse(y, true, out role) && testRoles.HasFlag(role)));
But I would like to use the Description attribute to compare. 但是我想使用Description属性进行比较。
How can I do this? 我怎样才能做到这一点?
Thank You 谢谢
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.