string - 我想检查是否满足 4 个条件应该发生什么
问题描述
我还是 c# 的新手,我正在尝试编写一个代码来检查我的 if 条件,如果满足 4 个条件,那么就会发生一些事情。这是我的代码:enter code here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NameTrans : MonoBehaviour {
public string thename;
public GameObject inputField;
public GameObject textDisplay;
public GameObject textDisplay2;
// Use this for initialization
public void Showname () {
thename = inputField.GetComponent<Text>().text;
if (thename.ToUpper().Contains("Man".ToUpper()) || thename.ToUpper().Contains("Dog".ToUpper()))
{
textDisplay2.SetActive(false);
textDisplay.SetActive(true);
textDisplay.GetComponent<Text>().text = "WOrks" ;
}
else
{
textDisplay.SetActive(false);
textDisplay2.SetActive(true);
textDisplay2.GetComponent<Text>().text = "Not WORK" ;
}
}
}
解决方案
如果只需要满足 4 个条件中的一个,那么您已经在做正确的事情了。您只需要添加缺少的两个条件。
if((thename.ToUpper().Contains("Man".ToUpper())) ||
(thename.ToUpper().Contains("Dog".ToUpper())) ||
(thename.ToUpper().Contains("Cat".ToUpper())) ||
(thename.ToUpper().Contains("Fish".ToUpper())))
{
//do something
}
else
{
//do something else
}
如果需要满足所有 4 个条件,则需要用“&&”而不是“||”连接条件。
if((thename.ToUpper().Contains("Man".ToUpper())) &&
(thename.ToUpper().Contains("Dog".ToUpper())) &&
(thename.ToUpper().Contains("Cat".ToUpper())) &&
(thename.ToUpper().Contains("Fish".ToUpper())))
{
//do something
}
else
{
//do something else
}
更新新信息 如果您想检查 x 条件中的任何 4 个是否为真,我可能会执行以下操作:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NameTrans : MonoBehaviour {
public string thename;
public GameObject inputField;
public GameObject textDisplay;
public GameObject textDisplay2;
private string[] conditions;
private int counter;
// Use this for initialization
public void Showname () {
thename = inputField.GetComponent<Text>().text;
conditions = {"Man", "Dog", "Cat", "Fish", "Goat",
"Frog", "Bird", "Alligator"};
counter = 0;
foreach(string cond in conditions)
{
if (thename.ToUpper().Contains(cond.ToUpper())
{
counter += 1;
if (counter >= 4)
{
break;
}
}
}
if (counter >= 4)
{
textDisplay2.SetActive(false);
textDisplay.SetActive(true);
textDisplay.GetComponent<Text>().text = "WOrks" ;
}
else
{
textDisplay.SetActive(false);
textDisplay2.SetActive(true);
textDisplay2.GetComponent<Text>().text = "Not WORK" ;
}
}
}
推荐阅读
- excel - 如何从两列中获取excel中的不同计数
- c# - Visual Studio 2015 发布输出 setup.exe 有错误
- heroku - 为什么我的应用程序的 IP 地址不会在后续请求中更改?
- login - 在 VBscript 中使用 GetElementByName 时需要对象
- python - 在训练周期的一部分之后运行评估
- git - `git diff tag` 中的标签指的是哪里?它如何找到标签指向的位置?
- sql - 如何替换确切的字符串
- node.js - 在 Mongoose 内部查找中放松身心
- sql - 在 SQLite3 的寄存器中存储带有 SQL 代码的字符串
- java - Java SE 中的事务类型