C# - 如果语句查询有关变量名重复

Ine*_*elp 1 c# variables if-statement repeat

有没有更简洁的方法来检查x是"a","b","c","d"还是"e"?

if (x == "a" | x == "b" | x == "c" | x == "d" | x == "e"){//do something}
Run Code Online (Sandbox Code Playgroud)

基本上我想知道我是否可以表达相同的if语句而不重复变量名x.

Ani*_*Ani 5

怎么样:

string[] whiteList = { "a", "b", "c", "d", "e" };

if(whiteList.Contains(x))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

您可以考虑使用一个HashSet<string>或类似的,并在字段中缓存对它的引用以提高性能(为您提供O(1)Contains操作并避免分配,填充集合).

//Field
HashSet<string> _whiteList = new HashSet<string> { "a", "b", "c", "d", "e" };

....

// In a method:
if(_whiteList.Contains(x))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)