Simply check for multiple statements C#

倖福魔咒の 提交于 2020-01-21 23:54:08

问题


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")

making a list or something and checking if map[playerX-1, playerY] is equal to any of the objects in it or something.

Thanks for the help in advance. Lukas Leder


回答1:


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"
};

Then use:

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.




回答2:


Jep, as @mjwills pointed out.

In fact, all IList or IDictionary descendants and similar have a Contains method. So its your choice which type of list or set fits best your needs.

A list for example is instanciated List<string> a = new List<string>(); a.Add("b");



来源:https://stackoverflow.com/questions/46828719/simply-check-for-multiple-statements-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!