c# 获取所有大于给定值的枚举值?

发布于 2024-11-26 11:17:02 字数 589 浏览 4 评论 0原文

我有以下成员角色枚举:

public enum RoleName
{
    RegisteredUser,
    Moderator,
    Administrator,
    Owner
}

我希望能够获取大于或等于给定角色的所有角色。

例如,我输入 Administrator,然后得到一个带有 RoleName.AdministrationRoleName.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

彩虹直至黑白 2024-12-03 11:17:02

可能取决于 .NET 的版本。但这对我来说非常有效:

不需要转换或使用特殊技巧。只需与通常的运算符进行比较即可:

using System;

enum Test { a1, a2, a3, a4 }

class Program
{
    static void Main(string[] args)
    {
        Test a = Test.a2;

        Console.WriteLine((a > Test.a1));
        Console.WriteLine((a > Test.a2));
        Console.WriteLine((a > Test.a3));
        Console.WriteLine((a > Test.a4));

        Console.ReadKey();
    }
}

输出:

True
False
False
False

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:

using System;

enum Test { a1, a2, a3, a4 }

class Program
{
    static void Main(string[] args)
    {
        Test a = Test.a2;

        Console.WriteLine((a > Test.a1));
        Console.WriteLine((a > Test.a2));
        Console.WriteLine((a > Test.a3));
        Console.WriteLine((a > Test.a4));

        Console.ReadKey();
    }
}

Output:

True
False
False
False
听风念你 2024-12-03 11:17:02

您可以使用以下帮助程序方法为您提供一组允许给定角色的角色:

    private IEnumerable<RoleName> AllAllowedRoles(RoleName level)
    {
        return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);
    } 

然后将它们全部分配给用户。

You can use the following helper method to give you a set of roles allowed for a given role:

    private IEnumerable<RoleName> AllAllowedRoles(RoleName level)
    {
        return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);
    } 

And then assign all of them to the user.

最冷一天 2024-12-03 11:17:02

为了更好地定义哪个角色比另一个角色更大,您需要为您的角色分配数值,如下所示:

public enum RoleName
{
    RegisteredUser = 2,
    Moderator = 4,
    Administrator = 8,
    Owner = 16
}

现在,如果您将 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:

public enum RoleName
{
    RegisteredUser = 2,
    Moderator = 4,
    Administrator = 8,
    Owner = 16
}

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.

半夏半凉 2024-12-03 11:17:02

与此一起去:

    public static void AddUserToRole(string username, RoleName level)
    {
        var roles = RolesLesserThanOrEqualTo(level);

        foreach (var role in roles)
        {
            Roles.AddUserToRole(username, role.Name());
        }
    }

    public static IEnumerable<RoleName> RolesLesserThanOrEqualTo(RoleName level)
    {
        return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);
    }

went with this:

    public static void AddUserToRole(string username, RoleName level)
    {
        var roles = RolesLesserThanOrEqualTo(level);

        foreach (var role in roles)
        {
            Roles.AddUserToRole(username, role.Name());
        }
    }

    public static IEnumerable<RoleName> RolesLesserThanOrEqualTo(RoleName level)
    {
        return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);
    }
翻身的咸鱼 2024-12-03 11:17:02

您的代码完全正确,只是您需要 Cast() 而不需要 ToList()

Your code is exactly correct, except that you need to Cast<int>() and you don't need ToList().

仙气飘飘 2024-12-03 11:17:02
public enum RoleName : int
{
    RegisteredUser = 7,
    Moderator = 8,
    Administrator = 9,
    Owner = 10
}

 public List<RoleName> GetGreaterOrEqual(RoleName role)
    {
        List<RoleName> list = new List<RoleName>();
        foreach (RoleName rn in Enum.GetValues(typeof(RoleName)))
        {
            if(rn >= role)
                list.Add(rn);
        }
        return list;
    }

您可以检查一下您可以循环遍历所有枚举值吗?

public enum RoleName : int
{
    RegisteredUser = 7,
    Moderator = 8,
    Administrator = 9,
    Owner = 10
}

 public List<RoleName> GetGreaterOrEqual(RoleName role)
    {
        List<RoleName> list = new List<RoleName>();
        foreach (RoleName rn in Enum.GetValues(typeof(RoleName)))
        {
            if(rn >= role)
                list.Add(rn);
        }
        return list;
    }

You could check this out Can you loop through all enum values?

清醇 2024-12-03 11:17:02

您必须考虑枚举的基础类型。因此:

static IEnumerable<T> Get<T>(T value) where T : struct {
    Type underlyingType = Enum.GetUnderlyingType(typeof(T));
    var compareToMethod = underlyingType.GetMethod(
                              "CompareTo",
                              new[] { underlyingType }
                          );
    var values = Enum.GetValues(typeof(T));
    for (int index = 0; index < values.Length; index++) {
        int comparison = (int)compareToMethod.Invoke(
            Convert.ChangeType(value, underlyingType),
            new object[] { values.GetValue(index) }
        );
        if (comparison >= 0) {
            yield return (T)values.GetValue(index);
        }
     }
 }

我不想想出一个好名字,但这很有效:

var largerValues = Get<RoleName>(RoleName.Moderator);
foreach(var largerValue in largerValues) {
    Console.WriteLine(largerValue);
}

You have to take into consideration the underlying type of the enum. Thus:

static IEnumerable<T> Get<T>(T value) where T : struct {
    Type underlyingType = Enum.GetUnderlyingType(typeof(T));
    var compareToMethod = underlyingType.GetMethod(
                              "CompareTo",
                              new[] { underlyingType }
                          );
    var values = Enum.GetValues(typeof(T));
    for (int index = 0; index < values.Length; index++) {
        int comparison = (int)compareToMethod.Invoke(
            Convert.ChangeType(value, underlyingType),
            new object[] { values.GetValue(index) }
        );
        if (comparison >= 0) {
            yield return (T)values.GetValue(index);
        }
     }
 }

I didn't feel like trying to come up with a good name, but this works:

var largerValues = Get<RoleName>(RoleName.Moderator);
foreach(var largerValue in largerValues) {
    Console.WriteLine(largerValue);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文