我是 C# 的新手,但似乎无法找到有关此问题的任何信息。这是我正在尝试做的事情:
string testString = txtBox1.Text;
string testString2 = txtBox2.Text;
if ((testString == "") || (testString2 == ""))
{
MessageBox.Show("You must enter a value into both boxes");
return;
}
基本上我需要检查 txtBox1 或 txtBox2 是否为空。但是我在运行它时遇到错误。执行此操作的正确方法是什么(或者我的方法完全错误)?
最佳答案
既然你想检查文本框是否包含任何值,你的代码应该完成这项工作。您应该更具体地说明您遇到的错误。您还可以:
if(textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
MessageBox.Show("You must enter a value into both boxes");
}
编辑 2:基于@JonSkeet 评论:
根据 OP 未经编辑的原始帖子,不需要使用 string.Compare。 String.Equals如果要比较字符串,应该可以完成这项工作,StringComparison
可用于忽略比较的大小写。 string.Compare 应用于顺序比较。
本来这个问题包含这个比较,
string testString = "This is a test";
string testString2 = "This is not a test";
if (testString == testString2)
{
//do some stuff;
}
if语句可以替换为
if(testString.Equals(testString2))
或以下忽略大小写。
if(testString.Equals(testString2,StringComparison.InvariantCultureIgnoreCase))
关于c# - 将 C# 中的字符串与 if 语句中的 OR 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11283764/