[英]C# string.length > 0 seen as boolean
I am new to C# but not to programming. 我是C#的新手,但不是编程。 When I compare the lengths of two strings in the code below, I get the error:
当我比较下面代码中两个字符串的长度时,我得到错误:
Operator '&' cannot be applied to operands of type 'bool' and 'int'
运算符'&'不能应用于'bool'和'int'类型的操作数
Apparently string1.Length > 0
is seen as a boolean in this context. 显然
string1.Length > 0
在此上下文中被视为布尔值。
How should I perform this comparison? 我该如何进行这种比较?
if (string1.Length > 0 & string2.Length = 0)
{
//Do Something
}
The reason for the error is because you have written =
when you meant ==
. 出错的原因是因为你写了
=
当你的意思是==
。 In C# 在C#中
string1.Length > 0 & string2.Length = 0
means 手段
(string1.Length > 0) & (string2.Length = 0)
The type of the left side is bool
and the type of the right side is int
, which cannot be &
-ed together, hence the error. 类型左侧的是
bool
和右侧的类型是int
,不能&
-ed在一起,因此,该错误。 Of course even if you managed to get past that, Length
cannot be the target of an assignment either. 当然,即使你设法超越了它,
Length
也不能成为任务的目标。
Use ==
to test for equality. 使用
==
来测试是否相等。 =
is assignment. =
是作业。
Consider also using &&
instead of &
. 考虑也使用
&&
而不是&
。 The meaning of x & y
is "evaluate both, the result is true
if both are true
and false
otherwise". 的含义
x & y
是“同时评估,结果是true
,如果都是true
和false
,否则”。 The meaning of x && y
is "evaluate the left side; if it is false
then the result is false
so do not evaluate the right side. If the left side is true
then proceed as &
does." x && y
的含义是“评估左侧;如果它是false
则结果为false
因此不评估右侧。如果左侧为true
则继续作为&
。”。
When applied to integers, the &
operator in C# is a bitwise AND
, not a logical AND
. 当应用于整数时,C#中的
&
运算符是按位AND
,而不是逻辑AND
。 Also =
is an assignment, not an equality comparison operator. 另外
=
是赋值,而不是相等比较运算符。 The string1.Length > 0
expression is indeed an expression of boolean type, while the assignment is integer (because 0
is integer). string1.Length > 0
表达式确实是布尔类型的表达式,而赋值是整数(因为0
是整数)。
What you need is 你需要的是什么
if (string1.Length > 0 && string2.Length == 0)
You probably meant to do this: 你可能打算这样做:
if (string1.Length > 0 && string2.Length == 0)
{
//Do Something
}
In C#, the =
operator is just for assignment. 在C#中,
=
运算符仅用于赋值。 The ==
is used for equality comparisons. ==
用于相等比较。 You probably also want to use the &&
operator instead of &
( &&
will skip the second condition if the first condition evaluates to false). 您可能还想使用
&&
运算符而不是&
(如果第一个条件的计算结果为false,则&&
将跳过第二个条件)。
However, if really want to 'compare the lengths of the strings', you can just do this: 但是,如果真的想“比较字符串的长度”,你可以这样做:
if (string1.Length > string2.Length)
{
//Do Something
}
这将解决您的问题。
if(string1.Length > 0 && string2.Length == 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.