可以防止非位掩码字段上的意外按位运算符吗?
在 C# 中,建议将 [Flags] 属性添加到位掩码枚举,如下所示:
[Flags]
public enum Condiments
{
None = 0,
Ketchup = 1,
Mustard = 2,
Mayo = 4,
Pickle = 8,
AllTheWay = 15
}
我发现我的代码在没有 [Flags]
属性的枚举上错误地执行了位操作,而该属性根本不是位掩码(第一=1,第二=2,第三=3,等等)。这在逻辑上当然是错误的,但编译器完全可以接受。
我想知道是否有任何方法可以利用 [Flags]
属性或其他方法将其转变为编译时错误/警告。我不知道从哪里开始,但似乎应该是可行的,所以任何帮助将不胜感激。
In C# you are recommended to add the [Flags] attribute to bitmask enumerations, like so:
[Flags]
public enum Condiments
{
None = 0,
Ketchup = 1,
Mustard = 2,
Mayo = 4,
Pickle = 8,
AllTheWay = 15
}
I discovered I had code that erroneously performed bitwise operations on an enumeration without the [Flags]
attribute that was not a bitmask at all (First=1, Second=2, Third=3, etc.). This was of course logically wrong, but perfectly acceptable to the compiler.
I'm wondering if there's any way to leverage the [Flags]
attribute, or some other approach, to turn this into a compile-time error/warning. I don't know where to begin, but it seems like it should be doable, so any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议进行此“自定义”检查,其中编译器无法找出问题使用 http://research.microsoft.com/en-us/projects/contracts/。代码合同,如果可以的话。
I would suggest for this "custom" checks, where compiler is not able to figure out the problem use http://research.microsoft.com/en-us/projects/contracts/. CodeContracts, if you can.