c# - 如何在枚举和 int 上使用按位或?

标签 c# enums binary-operators enum-flags

我有一个名为 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/

相关文章:

c# - 如何在 c#.net 中获取 javascript 确认弹出窗口值

java - 用 BinaryOperator 替换 switch

c# - CefSharp网页元素点击

c# - WPF如何将自己的对象暴露给其他窗口

c++ - 类中的枚举,具有显式作用域,C++11 之前的版本?

enums - 在 Kotlin 中直接引用枚举实例,无需类

c++ - 带有截断下溢的字符减法

arrays - 二元运算符 '!=' 不能应用于两个 '[[String]]' 操作数

c# - c#中的并行任务和线程安全

Python.Runtime.PythonException : since Python. NET 3.0 int 无法隐式转换为 Enum。使用枚举(int_value)