只需检查多个语句C# [英] Simply check for multiple statements C#
问题描述
目前正在开发一款小型主机游戏,想知道是否有人有一种简单的方法来缩短此类内容:
Currently working on a small console game and was wondering if anyone has a simple way to shorten something like this:
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]
是否等于其中的任何对象或物.
making a list or something and checking if map[playerX-1, playerY]
is equal to any of the objects in it or something.
非常感谢您的帮助. 卢卡斯·莱德(Lukas Leder)
Thanks for the help in advance. Lukas Leder
推荐答案
您感兴趣的特定匹配值(R1
,Z1
等)应填充到HashSet
中.
The particular matching values you are interested in (R1
, Z1
etc) should be populated into a 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
has a consistently fast Contains
function (shown above) which will suit your purposes. As @FilipCordas mentions below, you should consider declaring this HashSet
as a static readonly
field to ensure you only need to initialise it once.
这篇关于只需检查多个语句C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!