if语句中的三元运算符不会产生任何结果

时间:2016-07-09 18:29:32

标签: c# if-statement ternary-operator

好吧,我可能认为这一切都错了,但我似乎无法找到一个好的解决方案,所以任何指针都会有所帮助。我的代码中有以下声明:

if (!mapDict.ContainsKey(_thisRoom.Item1))
        {

            MapGraphItem roomMGI = new MapGraphItem();


            var rndOrderRooms = roomList.OrderBy(i => rnd.Next());
            foreach (MapGraphItem room in rndOrderRooms)
            {
                if (!room._flags.IsFlagSet(GlobalValues.MapTileType.start) && !room._flags.IsFlagSet(GlobalValues.MapTileType.exit)
                    && ((_thisRoom.Item2 == 'N') ? room._north : (_thisRoom.Item2 == 'S') ? room._south : (_thisRoom.Item2 == 'E') ? room._east : room._west)
                    && ((mapOpenings.Count < 4) : !room._flags.IsFlagSet(GlobalValues.MapTileType.deadend) ? *ignore this section*))
                {
                    roomMGI = room;
                    earlyRooms.Add(room);
                    goto Exit;
                }
            }

            Exit:
            //MapGraphItem _room = earlyRooms[rnd.Next(0, earlyRooms.Count)];

            GameObject _roomGO = (GameObject)Instantiate(roomMGI.gameObject, _thisRoom.Item1, Quaternion.identity);
            roomMGI._position = GlobalValues.MapTilePos.Early;
            mapDict.Add(_roomGO.transform.position, roomMGI);

            _mapUsed++;

            if (roomMGI._north) _n = true;
            if (roomMGI._south) _s = true;
            if (roomMGI._east) _e = true;
            if (roomMGI._west) _w = true;

            Debug.Log ("Early room added at: " + _thisRoom.Item1.ToString() + " N? " + (_n ? "yes" : "no") + " S? " + (_s ? "yes" : "no") + 
                " E? " + (_e ? "yes" : "no") + " W? " + (_w ? "yes" : "no"));

            GetRoomOpenings(_roomGO.transform.position, _n, _s, _e, _w);

            _tiles--;
        }

基本上,*ignore this section*区域意味着我不想发生任何事情。

换句话说,假设if的前两行是正确的,如果.Count小于4,则还有一个附加条件。如果.Count为4或更多,则不需要该条件。

我无法将其设置为相反,只是room._flags.IsFlagSet(GlobalValues.MapTileType.deadend),因为我不希望它被迫成为死胡同。我只是想确保如果剩下的mapOpening少于四个,那就不是死路一条了。

2 个答案:

答案 0 :(得分:2)

你可以改写

((mapOpenings.Count < 4)) ? !room._flags.IsFlagSet(GlobalValues.MapTileType.deadend) : *ignore this section*)

as

((mapOpenings.Count < 4) || !room._flags.IsFlagSet(GlobalValues.MapTileType.deadend))

答案 1 :(得分:0)

下面的代码都回答了问题并重构了你的代码,这在易读部门迫切需要改进(正如许多人在评论中所指出的那样)。

if (room._flags.IsFlagSet(GlobalValues.MapTileType.start) {
 return;
}

if (room._flags.IsFlagSet(GlobalValues.MapTileType.exit) {
 return;
}

bool dirFlag = false;
if (_thisRoom.Item2 == 'N') {
 dirFlag = room._north;
}else if (_thisRoom.Item2 == 'S') {
 dirFlag = room._south;
}else if (_thisRoom.Item2 == 'E') {
 dirFlag = room._east;
}else {
 dirFlag = room._west;
}

if (!dirFlag) {
 return;
}

if (mapOpenings.Count < 4 && room._flags.IsFlagSet(GlobalValues.MapTileType.deadend)) {
 return;
}

roomMGI = room;
earlyRooms.Add(room);
goto Exit;