c# - 将 C# 中的字符串与 if 语句中的 OR 进行比较

标签 c# string

我是 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/

相关文章:

c# - 我在哪里可以在 azure 应用程序中找到 "authenticationKey"值来创建 "ClientCredential"对象

c - 如何在 C 中将 char* 拆分为子字符串?

c - 如何在 C 函数中使用未定义的字符串大小?

c# - 在 C# 中找到两个集合的补集的最快方法

Java 8 : Why can't I parse this binary string into a long?

java - java中的字符串截断

java - 拆分字符串方法的奇怪行为

c# - X分钟后黑屏

c# - 使用通用回调是一种不好的形式吗?

c# - 解析器错误消息 : Could not create type 'xxx'