我有一个名为e4view
的标志Enum
和一个名为Role
的扩展方法,该方法有一个Role枚举和一个像标志一样工作的int,只包含一个和零,其中每个1代表一个人的角色。我希望该方法将角色添加到int,以便AddRole
例如返回 1100 。
AddRole(Role.Grandmother, 1000)
我尝试这样做:
[Flags]
public enum Role
{
Mother = 1,
Daughter = 2,
Grandmother = 4,
Sister = 8,
}
但是这只会返回1004。有人知道正确的方法吗? (我无法避免使用“ binary ish” int表示形式,因为这是实体存储在(非常古老且不可接触的)数据库中的方式)
答案 0 :(得分:3)
因此,您实际遇到的问题是如何将十进制值(如1000
)解释为二进制表示形式。
您可以通过将其转换为字符串,然后让Convert.ToInt32()重载并接受 base 参数作为二进制值来重新解析它:
int i = 1000;
int b = Convert.ToInt32(i.ToString(), 2); // interprete the string as a binary value
// b = 8