gpt4 book ai didi

C# string.length > 0 被视为 bool 值

转载 作者:太空狗 更新时间:2023-10-29 23:56:38 24 4
gpt4 key购买 nike

我是 C# 新手,但不是编程新手。当我在下面的代码中比较两个字符串的长度时,出现错误:

Operator '&' cannot be applied to operands of type 'bool' and 'int'

显然 string1.Length > 0 在此上下文中被视为 bool 值。

我应该如何进行比较?

if (string1.Length > 0 & string2.Length = 0)
{
//Do Something
}

最佳答案

错误的原因是因为你写的是=,而你的意思是==。在 C# 中

string1.Length > 0 & string2.Length = 0

表示

(string1.Length > 0) & (string2.Length = 0)

左边的类型是bool,右边的类型是int,不能用&合并,因此错误。当然,即使您设法克服了这一点,Length 也不能成为赋值的目标。

使用 == 来测试相等性。 = 是赋值。

也可以考虑使用 && 而不是 &x & y 的含义是“评估两者,如果两者都是true,则结果为true,否则为false ”。 x && y 的意思是“计算左边;如果它是 false 那么结果是 false 所以不要计算右边. 如果左侧为 true,则按照 & 的方式进行。”

关于C# string.length > 0 被视为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16929687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com