我有一个名为 Role
的标记 Enum
和一个名为 AddRole
的扩展方法,它采用 Role 枚举和一个 int,其工作方式类似于flag 并且只包含 1 和 0,其中每个 1 代表一个人拥有的角色。我想要将角色添加到 int 的方法,例如 AddRole(Role.Grandmother, 1000)
返回 1100。
[Flags]
public enum Role
{
Mother = 1,
Daughter = 2,
Grandmother = 4,
Sister = 8,
}
我试过这样做:
public static int AddRole(this Role newRole, int currentRoles)
{
return (int)((Role)currentRoles | newRole);
}
但这只会返回 1004。有谁知道正确的方法吗? (我无法避免“二进制 ish”int 表示,因为这是实体存储在(非常古老且不可触及的)数据库中的方式)
最佳答案
因此,您遇到的实际问题是如何将十进制值(如 1000
)解释为二进制表示形式。
您可以通过将其转换为字符串然后让 Convert.ToInt32() 来做到这一点采用 base 参数的重载再次将其解析为二进制值:
int i = 1000;
int b = Convert.ToInt32(i.ToString(), 2); // interprete the string as a binary value
// b = 8
关于c# - 如何在枚举和 int 上使用按位或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56270958/