gpt4 book ai didi

c# - 如何在 .NET 枚举中搜索正确的方法

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:33 25 4
gpt4 key购买 nike

我想给我的“用户”对象一些权限。该权限在枚举中定义。为了更容易理解,我将发布我的代码。

public  class User
{
public string UserName { get; set; }
public string Password { get; set; }
public UserRights Permissions { get; set; }

public override string ToString()
{
return "Username: " + UserName + " - Password: " + Password + " - Permisssions: " + Permissions;
}
}

public enum UserRights
{
Admin,
SmallAdmin,
SimpleUser,
JustDummy
}

public class EnumFinder
{
public List<User> Users = new List<User>();

public EnumFinder()
{
CreateUsers();

List<User> search = (from a in Users where a.Permissions == UserRights.SimpleUser select a).ToList<User>();
foreach (User user in search)
{
Console.WriteLine(user.ToString());
}
}

/// <summary>
/// Create some example users and put the objects into User's list
/// </summary>
private void CreateUsers()
{
var user1 = new User();
user1.UserName = "user1";
user1.Password = "password1";
user1.Permissions = UserRights.Admin;

var user2 = new User();
user2.UserName = "user2";
user2.Password = "password2";
user2.Permissions = UserRights.SmallAdmin | UserRights.JustDummy;

var user3 = new User();
user3.UserName = "user3";
user3.Password = "password3";
user3.Permissions = UserRights.SimpleUser;
Users.Add(user1);
Users.Add(user2);
Users.Add(user3);
}
}

因此,如您所见,我在我的用户列表中添加了一些示例用户。他们每个人都有不同的权限。现在假设我想搜索每个具有“管理员”权限的用户。这很好用(对于那个用户):

List<User> search = (from a in Users where a.Permissions == UserRights.Admin select a).ToList<User>();

但是假设我正在寻找具有 SmallAdmin 权限的用户。所以我试了一下:

    List<User> search = (from a in Users where a.Permissions == UserRights.SmallAdmin select a).ToList<User>();

在这种情况下,没有找到用户。为什么不?感谢您的帮助。

最佳答案

[Flags] 属性标记您的枚举并使用HasFlag方法代替

List<User> search = (from a in Users 
where a.Permissions.HasFlag(UserRights.SmallAdmin)
select a).ToList<User>();

关于c# - 如何在 .NET 枚举中搜索正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com