c# 获取所有大于给定值的枚举值?
我有以下成员角色枚举:
public enum RoleName
{
RegisteredUser,
Moderator,
Administrator,
Owner
}
我希望能够获取大于或等于给定角色的所有角色。
例如,我输入 Administrator,然后得到一个带有 RoleName.Administration
和 RoleName.Owner
的 IEnumerable
:
public static void AddUserToRole(string username, RoleName level)
{
var roles = Enum.GetValues(typeof(RoleName)).Cast<R>().ToList().Where(role => level > role);
foreach (var role in roles)
{
Roles.AddUserToRole(username, role);
}
}
I have the following enumeration of membership roles:
public enum RoleName
{
RegisteredUser,
Moderator,
Administrator,
Owner
}
I want to be able to fetch all roles greater than or equal to a given role.
For instance I input Administrator and I get an IEnumerable with RoleName.Administration
and RoleName.Owner
Something of this sort:
public static void AddUserToRole(string username, RoleName level)
{
var roles = Enum.GetValues(typeof(RoleName)).Cast<R>().ToList().Where(role => level > role);
foreach (var role in roles)
{
Roles.AddUserToRole(username, role);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
可能取决于 .NET 的版本。但这对我来说非常有效:
不需要转换或使用特殊技巧。只需与通常的运算符进行比较即可:
输出:
Probably depending on version of .NET. But this works very well for me:
There is no need to convert or to use special tricks. Just compare with the usual operators:
Output:
您可以使用以下帮助程序方法为您提供一组允许给定角色的角色:
然后将它们全部分配给用户。
You can use the following helper method to give you a set of roles allowed for a given role:
And then assign all of them to the user.
为了更好地定义哪个角色比另一个角色更大,您需要为您的角色分配数值,如下所示:
现在,如果您将 RoleName 类型的任何实例强制转换为 (int),您将得到数值,因此您将能够将它们相互比较。
注:
1. 这里我使用 2 的幂作为值,以允许使用按位运算符组合 RoleName。
in order to have a better definition of which role is greater than the other you need to assign numeric values to your roles like this:
Now if you cast any instance of type RoleName to (int) you will get the numeric value and therefore you will be able to compare them against each other.
Note:
1. Here I use powers of 2 as values to allow combining RoleNames using bit-wise operators.
与此一起去:
went with this:
您的代码完全正确,只是您需要
Cast()
而不需要ToList()
。Your code is exactly correct, except that you need to
Cast<int>()
and you don't needToList()
.您可以检查一下您可以循环遍历所有枚举值吗?
You could check this out Can you loop through all enum values?
您必须考虑枚举的基础类型。因此:
我不想想出一个好名字,但这很有效:
You have to take into consideration the underlying type of the enum. Thus:
I didn't feel like trying to come up with a good name, but this works: