根据另一个变量为变量赋值

Assign values to variables depending on another variable

我有一个关于赋值的快速问题。
在我的新程序中,我试图根据整数的值为布尔值赋值。这是我的意思的一个简单例子:

bool northDoorAvailable;
int roomLocation;

// set player Location in some code
roomLocation = 2;

// now set if the north door is available

这只能通过我写了很多 if 语句的函数实现吗?

public void checkDoors() 
{
    if ( roomLocation == 1 )
    {
        northDoorAvailable = false;
    }
    if ( roomLocation == 2 )
    {
        northDoorAvailable = true;
    }
}

或者这个过程可以自动化吗?

很高兴收到任何回复。

更好的语法在很大程度上取决于所有可能的条件。现在你可以使用

 northDoorAvailable = (roomLocation == 2);

 northDoorAvailable = (roomLocation != 1);

因为X == Yreturnstruefalse取决于两者是否"equal"。 (反之亦然 !=

但是如果 roomLocation3 呢? 4?

一般来说,通常可以将这些条件简化为一个逻辑表达式,但可能总是是这种情况.一种简化的方法是将所有可能的条件放在一个 "truth table" 中,然后查看等效的逻辑表达式是什么。

there would be others so if roomlocation != possibleLocations it would do northDoorAvailable = false

我假设 possibleLocations 是一个 集合 如果是整数,并且如果它 包含 roomlocation那么 northDoorAvailable 将是 true。在这种情况下,您可以使用

northDoorAvailable = (possibleLocations.Contains(roomlocation));

您可以为此使用字典:

public class MyGameClass
{
    private Dictionary<int, bool> _northDoorAvailable = new Dictionary<int, bool>();

    public MyGameClass()
    {
        _northDoorAvailable[1] = false;
        _northDoorAvailalbe[2] = true;
        _northDoorAvailable[3] = false;
        _northDoorAvailable[4] = false;
        _northDoorAvailable[5] = false;
    }

    public bool IsNorthDoorAvailable(int room)
    {
        bool available = false;
        _northDoorAvailable.TryGetValue(room, out available);
        return available;
    }
}

字典是一个 key/value 存储,在这种情况下,键是房间号,值(= 标记的另一边)是门是否可用。无论您使用什么 class,您都可以在构造函数方法中快速将案例添加到字典中,并且您可以在内部或通过 IsNorthDoorAvailable 方法公开访问字典。

你可以做的是有一个排序列表并解析一个单词 doc 或 db table 与房间列表及其相应的布尔值然后循环列表

1 - 真

2 - 真

3 - 错误

等...

SortedList<int, bool> roomsList = new SortedList<int, bool>();

using (StreamReader reader = new StreamReader(@"C:\temp\RoomList.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] rooms = line.Split('-');
                roomsList.Add(int.Parse(rooms[0]), bool.Parse(rooms[1]));
            }
        }