了解C#中的布尔键用法 [英] to understand the Boolean key use in C#
问题描述
大家好,
我正在尝试在C#.Net中执行以下代码
Hi All,
I m trying to execute following code in C# .Net
private void txtRollNumber_KeyDown(object sender, KeyEventArgs e)
{
label1.Enabled = true;
bool result = false;
if (txtRollNumber.Text == false)
{
label1.Text="Please Enter value in Roll Number";
txtRollNumber.Select();
}
else
{
txtname.Select();
}
}
但它在这一行中显示错误(txtRollNumber.Text == false),它表明
运算符"=="不能应用于类型为字符串"和布尔"的操作数
请帮我该怎么办?
谢谢&问候
Indrajit
but it shows an error in this line (txtRollNumber.Text == false) it shows that
Operator ''=='' cannot be applied to operands of type ''string'' and ''bool''
Please help what should I do ?
Thanks & Regards
Indrajit
推荐答案
您可以将字符串与布尔值进行比较,就像对苹果和计算机(:rolleyes:)一样. 要解决此问题,请将一个表达式与另一个相同类型的表达式进行比较,例如
You can compare strings with booleans like you may do with apples and computers ( :rolleyes: ).
To fix the issue compare an expression with another of the same type, e.g.
// string to string comparison
if ( txtRollNumberTxt.Text == String.Empty )
或
or
// bool to bool comparison
if ( String.IsNullOrEmpty(txtRollNumberTxt.Text) == true )
请注意,上面的代码可能更简洁地表示为
Please note the above code maybe expressed more concisely with
if ( String.IsNullOrEmpty(txtRollNumberTxt.Text) )
尝试一下.
Try this.
private void txtRollNumber_KeyDown(object sender, KeyEventArgs e)
{
label1.Enabled = true;
bool result = false;
if (string.IsNullOrWhiteSpace(txtRollNumber.Text))
{
label1.Text="Please Enter value in Roll Number";
txtRollNumber.Select();
}
else
{
txtname.Select();
}
}
还有一件事.
String.IsNullOrWhiteSpace与String.IsNullOrEmpty.
String.IsNullOrWhiteSpace背后的代码是这样描述的:
One more thing.
String.IsNullOrWhiteSpace vs String.IsNullOrEmpty.
The code behind String.IsNullOrWhiteSpace is described like this:
return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
SIMPLEST ...
SIMPLEST...
if ( txtRollNumberTxt.Text.Trim() == String.Empty )
{
label1.Text="Please Enter value in Roll Number";
txtRollNumber.Select();
}
.
.
.
这篇关于了解C#中的布尔键用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!