C#左移运算符 [英] C# Left Shift Operator

查看:213
本文介绍了C#左移运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位同事写了一个我不完全理解的声明.不幸的是,他现在不可用,所以就在这里(名称已修改,我们正在Unity中开发游戏).

There's a statement a co-worker of mine wrote which I don't completely understand. Unfortunately he's not available right now, so here it is (with modified names, we're working on a game in Unity).

private readonly int FRUIT_LAYERS =
          (1 << LayerMask.NameToLayer("Apple"))
        | (1 << LayerMask.NameToLayer("Banana"));

NameToLayer接受一个字符串并返回一个整数.我一直看到左移运算符在右侧而不是在左侧使用常量整数,而我在Google上找到的所有示例都遵循这种方法.在这种情况下,我认为他正在将Apple和Banana推到相同的相对层上(稍后将用于过滤).将来会有更多的水果"可供选择.谁能给我解释这些线路上正在发生什么的奇妙的stackoverflowers?

NameToLayer takes a string and returns an integer. I've always seen left shift operators used with the constant integer on the right side, not the left, and all the examples I'm finding via Google follow that approach. In this case, I think he's pushing Apple and Banana onto the same relative layer (which I'll use later for filtering). In the future there would be more "fruits" to filter by. Any brilliant stackoverflowers who can give me an explanation of what's happening on those lines?

推荐答案

您的同事实际上是在使用int代替bool[32]来节省空间.您显示的代码块类似于

Your coworker is essentially using an int in place of a bool[32] to try to save on space. The block of code you show is analogous to

bool[] FRUIT_LAYERS = new bool[32];
FRUIT_LAYERS[LayerMask.NameToLayer("Apple")] = true;
FRUIT_LAYERS[LayerMask.NameToLayer("Banana")] = true;

您可能想考虑一种更像这样的模式:

You might want to consider a pattern more like this:

[Flags]
enum FruitLayers : int
{
    Apple = 1 << 0,
    Banana = 1 << 1,
    Kiwi = 1 << 2,
    ...
}

private readonly FruitLayers FRUIT_LAYERS = FruitLayers.Apple | FruitLayers.Banana;

这篇关于C#左移运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆