C#"或"运算符

San*_*ano -3 c# string operators

我有这个代码:

if (textBox1.Text == "one" || "two")
Run Code Online (Sandbox Code Playgroud)

我试过用|| 和| 添加更多字符串,但它表示它不能应用于"bool"和"string"类型的操作数.我怎样才能做到这一点?谢谢.

Sri*_*vel 6

试试这个

if (textBox1.Text == "one" || textBox1.Text == "two")
Run Code Online (Sandbox Code Playgroud)


Tig*_*ran 5

或者:

var strings = new List<string>() {"one", "two", "thee", .... "n"};
if(strings.Contains(textBox1.Text)){
}
Run Code Online (Sandbox Code Playgroud)


Tre*_*ley 5

您不能以我怀疑您正在尝试的方式组合运算符:

if (textBox1.Text == "one" || "two")
Run Code Online (Sandbox Code Playgroud)

您需要按如下方式限定每个条件:

if (textBox1.Text == "one" || textBox1.Text == "two")
Run Code Online (Sandbox Code Playgroud)

有很多方法可以使这更容易,请参阅此问题的答案以获取替代方法