C# 将字符串与其他两个字符串进行比较
所以我有这个代码部分:C# 将字符串与其他两个字符串进行比较,c#,if-statement,compare,C#,If Statement,Compare,所以我有这个代码部分: private int checkErrors() { int error = 0; if (!(nether.Text.Equals("true"))) { error += 1; } if (!(nether.Text.Equals("false"))) { error += 1; } if (!(fly.Text.Equals("true"))) { error
private int checkErrors() {
int error = 0;
if (!(nether.Text.Equals("true"))) { error += 1; }
if (!(nether.Text.Equals("false"))) { error += 1; }
if (!(fly.Text.Equals("true"))) { error += 1; }
if (!(fly.Text.Equals("false"))) { error += 1; }
if (!(achivments.Text.Equals("true"))) { error += 1; }
if (!(achivments.Text.Equals("false"))) { error += 1; }
if (!(whitelist.Text.Equals("true"))) { error += 1; }
if (!(whitelist.Text.Equals("false"))) { error += 1; }
if (!(pvp.Text.Equals("true"))) { error += 1; }
if (!(pvp.Text.Equals("false"))) { error += 1; }
if (!(commandBlock.Text.Equals("true"))) { error += 1; }
if (!(commandBlock.Text.Equals("false"))) { error += 1; }
if (!(spawnMonster.Text.Equals("true"))) { error += 1; }
if (!(spawnMonster.Text.Equals("false")) { error += 1; }
return error;
}
但无论如何,它都会让我明白,'error=7'
,因为当一条语句为真时,另一条语句为假
所以我的问题是:
有没有办法将两个字符串与第三个字符串进行比较
其他示例:我有字符串
userInput
,如果userInput
不等于“a”
或“b”
执行error+=1代码> 我怀疑你是在试图找到既不是“真”又不是“假”的案例。比如:
if (spawnMonster.Text != "true" && spawnMonster.Text != "false")
{
error++;
}
或者,表示一次条件,并将其应用于所有字符串:
var strings = new[] { nether.Text, fly.Text, achivments.Text, whitelist.Text
pvp.Text, commandBlock.Text, spawnMonster.Text };
return strings.Count(t => t != "true" && t != "false");
只有两条:
if (!nether.Text.Equals("true") && !nether.Text.Equals("false")) { error += 1; }
您可以使用的另一种方法是创建一个接受2个参数的函数。一个参数是userInput,另一个参数是userInput不应该是的值数组。它将返回1或0
例如:
public int isBadValue(string userInput, string[] goodValues){
if(Array.IndexOf(userInput) > -1){
return 0;
}
return 1;
}
在代码中,您可以执行如下操作:
string[] goodValues = {"a", "b"};
error += isBadValue("s", goodValues);
您可以轻松地添加更多好的值,函数将能够处理它。不确定好的值是否会根据输入字段发生变化,这就是为什么我没有将其包含在isBadValue函数中。我猜。。您的意思是Text
可以是true
,也可以是false
,如果不是error+=1
?这行中的“有没有办法将两个字符串与第三个字符串进行比较?”是什么意思?我有两个固定字符串,希望将它们与第三个可变字符串进行比较