c# - 简单地检查多个语句 C#

标签 c# arrays if-statement

目前正在开发一款小型主机游戏,想知道是否有人有一种简单的方法来缩短这样的内容:

if (map[playerX - 1, playerY] == "R1"
 || map[playerX - 1, playerY] == "R2"
 || map[playerX - 1, playerY] == "R3"
 || map[playerX - 1, playerY] == "Z1" 
 || map[playerX - 1, playerY] == "Z2" 
 || map[playerX - 1, playerY] == "Z3"
 || map[playerX - 1, playerY] == "S1 " 
 || map[playerX - 1, playerY] == "S2" 
 || map[playerX - 1, playerY] == "S3")

制作列表或其他内容并检查 map[playerX-1, playerY] 是否等于其中的任何对象或其他内容。

提前感谢您的帮助。 卢卡斯·莱德

最佳答案

您感兴趣的特定匹配值(R1Z1 等)应填充到 HashSet 中。

HashSet hashSet = new HashSet<string>
{
    "R1",
    "R2",
    "R3",
    "Z1",
    "Z2",
    "Z3",
    "S1 ", // I am unclear whether you want this space or not
    "S2",
    "S3"
};

然后使用:

if (hashSet.Contains(map[playerX - 1, playerY])

HashSet 具有始终如一的快速 Contains适合您目的的功能(如上所示)。正如 @FilipCordas 在下面提到的,您应该考虑将此 HashSet 声明为一个 static readonly 字段,以确保您只需要将其初始化一次。

关于c# - 简单地检查多个语句 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46828719/

相关文章:

javascript - 使用平均值、标准开发或回归来填充 Javascript 数组?

css - 在辅助方法中没有从 if else 获得所需的结果

ios - 基于 segue 标识符的条件

C# 事件处理器订阅管理

c# - system.invalidoperationexception : collection was modified; enumeration operation may not execute. 需要想法吗?

c# - LINQ 和 ExcelQueryFactory

c - 将指针的一个元素分配给同一指针的另一个元素

javascript - ASP + Jquery 聚焦 Gridview 中的下一个文本框

c++ - 从启动 C++ 的函数中删除动态分配的数组

javascript - li jquery 点击: if to switch