我几周前开始学习C#,现在需要构建一个"位集合"标志来处理算法中的不同情况。因此,我有两个选项:
enum RelativePositioning
{
LEFT = 0,
RIGHT = 1,
BOTTOM = 2,
TOP = 3,
FRONT = 4,
BACK = 5
}
pos = ((eye.X < minCorner.X ? 1 : 0) << (int) RelativePositioning.LEFT)
+ ((eye.X > maxCorner.X ? 1 : 0) << (int) RelativePositioning.RIGHT)
+ ((eye.Y < minCorner.Y ? 1 : 0) << (int) RelativePositioning.BOTTOM)
+ ((eye.Y > maxCorner.Y ? 1 : 0) << (int) RelativePositioning.TOP)
+ ((eye.Z < minCorner.Z ? 1 : 0) << (int) RelativePositioning.FRONT)
+ ((eye.Z > maxCorner.Z ? 1 : 0) << (int) RelativePositioning.BACK);
或者:
enum RelativePositioning
{
LEFT = 1,
RIGHT = 2,
BOTTOM = 4,
TOP = 8,
FRONT = 16,
BACK = 32
}
if (eye.X < minCorner.X) { pos += (int) RelativePositioning.LEFT; }
if (eye.X > maxCorner.X) { pos += (int) RelativePositioning.RIGHT; }
if (eye.Y < minCorner.Y) { pos += (int) RelativePositioning.BOTTOM; }
if (eye.Y > maxCorner.Y) { pos += (int) RelativePositioning.TOP; }
if (eye.Z > maxCorner.Z) { pos += (int) RelativePositioning.FRONT; }
if (eye.Z < minCorner.Z) { pos += (int) RelativePositioning.BACK; }
我本可以使用 ((eye.X > maxCorner.X) << 1)
这样的表达式,但是C#不允许将bool类型隐式转换为int类型,三目运算符则相似度更高。我的问题是:第一种方式是否比第二种方式性能更好?
谢谢
Tommaso