c# – Enum Flags负值
发布时间:2020-12-16 01:27:38 所属栏目:百科 来源:网络整理
导读:得到一个负数(-2147483392) 我不明白为什么它(正确)转换为标志枚举. 特定 [Flags]public enum ReasonEnum{ REASON1 = 1 0,REASON2 = 1 1,REASON3 = 1 2,//etc more flags //But the ones that matter for this are REASON9 = 1 8,REASON17 = 1 31 } 为什么以
得到一个负数(-2147483392)
我不明白为什么它(正确)转换为标志枚举. 特定 [Flags] public enum ReasonEnum { REASON1 = 1 << 0,REASON2 = 1 << 1,REASON3 = 1 << 2,//etc more flags //But the ones that matter for this are REASON9 = 1 << 8,REASON17 = 1 << 31 } 为什么以下正确报告REASON9和REASON17基于负数? var reason = -2147483392; ReasonEnum strReason = (ReasonEnum)reason; Console.WriteLine(strReason); .NET小提琴here 我说得对,因为这是一个从COM组件触发的事件原因属性,并且当作为枚举值进行转换时,它所投射的值是正确的(根据该事件).标志枚举是根据COM对象的SDK文档. COM对象是第三方,我无法控制数字,基于接口,它将始终作为INT提供 解决方法
最顶部的位集(在Int32的情况下为第31位)表示负数(有关详细信息,请参阅
two’s complement):
int reason = -2147483392; string bits = Convert.ToString(reason,2).PadLeft(32,'0'); Console.Write(bits); 结果: 10000000000000000000000100000000 ^ ^ | 8-th 31-th 所以你有 -2147483392 == (1 << 31) | (1 << 8) == REASON17 | REASON9 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |