C# 按位运算符
我一直在查看一些游戏编程代码,并看到了如下所示的枚举:
[Flags]
public enum CollisionCategories
{
Cat1 = (1 << 0),
Cat2 = (1 << 1),
Cat3 = (1 << 2),
Cat4 = (1 << 3),
...
}
现在,这是否与仅设置每个项目(例如 1, 2, 4, 8, ... )相同?后面的我也看过。我知道就性能而言,类似 string s = string.Empty
比 string s = ""
更好,但不确定枚举。
有什么想法吗?
非常感谢,
大卫
I've been looking over some game programming code and have seen enums as in:
[Flags]
public enum CollisionCategories
{
Cat1 = (1 << 0),
Cat2 = (1 << 1),
Cat3 = (1 << 2),
Cat4 = (1 << 3),
...
}
Now, would this not be the same as just setting each item like 1, 2, 4, 8, ... ? I've seen the later as well. I know doing something like string s = string.Empty
is better than string s = ""
as far as performance goes but not sure about the enum.
Any thoughts?
Thanks much,
David
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您对存储的值的看法是正确的。它不会对性能产生影响,因此这是一个可读性问题,在代码上下文中可能更有意义。
You are correct about the values that are stored. It would not make a difference in performance, so it is a readability issue that may make more sense in the context of the code.
当你得到更大的数字时,这就更容易了。
我确信 (1<<24) 比使用计算器计算并粘贴要简单。
It's just easier when you get to the larger numbers.
I'm sure that (1<< 24) is simpler than going to your calculator, calculating it, and pasting.
对于某些人来说,以这种方式设置它们比典型的 C 原始十六进制/十进制数字初始化更干净。 (0x1、0x4000 等)由于编译器识别文字并将其转换为纯数字,因此不存在性能缺陷,这只是风格问题。
For some people, setting them this way is just cleaner than the typical C raw hex/decimal number initialization. (0x1,0x4000,etc) Since the compiler recognizes a literal and turns them into plain numbers, there's no performance drawback, it's just a style matter.
是的,是一样的。
我个人会使用 1,2,4,8...,因为我认为这些数字是众所周知的,没有人会误解正在发生的事情。
性能是一样的。代码大小相同。
Yes it is the same.
I personally would use 1,2,4,8... because I think these numbers are so much well known that no one can misunderstand what's going on.
Performance is the same. Code size is the same.
是的,是一样的。只是为了让代码更具可读性。
Yes, it is the same. It's just so the code is more readable.
我认为 String.Empty 相当于 "" 编译器会识别文字并转换它......无论如何,这对你的枚举来说是一样的,这只是一个风格问题,在枚举的情况下它使它成为 100 %明确指出这些是我认为的位标志。
或者也许编码员对他的 2 的幂没有信心,并且懒得去计算它们。
I think String.Empty is equivalent to "" the compiler will recognise the literal and convert it..... Anyway, it's the same for you enum, it's just a question of style and in the case of the enum it makes it 100% explicit that these are bit flags I suppose.
Or maybe the coder wasn't confident with his powers of 2, and couldn't be bothered to work them out.
性能在这里不是问题。枚举被编译为常量,因此编译器正在执行这项工作,因此运行时性能没有差异。
替代方案可能是使用该功能,但由于这涉及代码,因此它不起作用:
枚举值必须是常量。
Performance is not an issue here. Enum is compiled as a constant so it is the compiler that is doing the job hence no difference in runtime performance.
Alternative could have been using the power but since that involves code, it would not work:
Enum values must be constants.