如何添加多个if可能性



我对C#还很陌生,我想帮助添加更多if可能性。如果这没有意义,这里是代码:

if (flatTextBox1.Text == "XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8")                
{
MessageBox.Show("Enjoy Goat Hub! Credits to oreo #####");
this.Hide();
Form3 form3 = new Form3();
Form3 main = form3;
main.Show();
}
else
{
MessageBox.Show("Invalid Key or Key Copied Incorrectly");
}

我想要if (flatTextBox1.Text == "XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8")等于多个事物。因此,如果用户在文本框中输入这两种可能性中的任何一种,它将允许他们访问表单3。

您可以在作用域之外创建一个字符串数组,并检查该数组是否包含它们的答案:

public string[] answers = {"XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8", "test", "test2"};

然后在你的方法:

if(answers.Contains(textBox1.Text)) {
MessageBox.Show("Enjoy Goat Hub! Credits to oreo #####");
this.Hide();
Form3 form3 = new Form3();
Form3 main = form3;
main.Show();
}

您可能正在if语句中寻找OR子句。例如

if (flatTextBox1.Text == "XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8" || flatTextBox1.Text == "something else")

这是一个简单的例子。一旦超过一个或两个值,您可能需要使用列表或数组之类的东西,并检查文本框内容是否与列表中的任何项目匹配

var keys = {
"XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8",
"...",
"...",
"etc"
};
if (!keys.Contains(flatTextBox1.Text))
{
MessageBox.Show("Invalid Key or Key Copied Incorrectly");
return; 
}
// If you make it here it's a success
//   and we've saved a level of indentation.

如果您在数据库或web服务中处理比较,效果会更好。如果密钥嵌入到代码中,聪明的人将能够找到它们。

我还建议将其抽象为自己的方法(这也会使稍后将其转移到DB/web服务变得更容易(:

bool IsValidKey(string input)
{
var keys = {
"XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8",
"...",
"...",
"etc"
};
return keys.Contains(input);
}

然后这样称呼它:

if (!IsValidKey(flatTextBox1.Text))
{
MessageBox.Show("Invalid Key or Key Copied Incorrectly");
return; 
}
//success 

ThePerplexedOne发布了一个可能更好的实现选项,但这里有另一个选项:

您可以为OR条件添加"||",或为AND条件添加"&&"。

在你的情况下,你会做一些类似的事情:

if (flatTextBox1.Text == "XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8" || 
flatTextBox1.Text == "myTest" || flatTextBox1.Text == "otherText")
{
MessageBox.Show("Enjoy Goat Hub! Credits to oreo #####");
this.Hide();
Form3 form3 = new Form3();
Form3 main = form3;
main.Show();
}
else
{
MessageBox.Show("Invalid Key or Key Copied Incorrectly");
}
if (flatTextBox1.Text == "XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8" || flatTextBox1.Text == "5s5dgGs55as4g4d844adsgd")
{
MessageBox.Show("Enjoy Goat Hub! Credits to oreo #####");
this.Hide();
Form3 form3 = new Form3();
form3.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid Key or Key Copied Incorrectly");
}

if (new string[] { "XeC2YfjcEtzD6Kw7zkCssjDgoRmdZcv8", "5s5dgGs55as4g4d844adsgd" }.Contains(flatTextBox1.Text))
{  
MessageBox.Show("Enjoy Goat Hub! Credits to oreo #####");
this.Close();
Form3 form3 = new Form3();
form3.Show();
}
else
{
MessageBox.Show("Invalid Key or Key Copied Incorrectly");
}

最新更新