AND 条件有问题
下面的代码:
if(var != "" && var.startswith("somestring"))
{ do something }
这段代码令人不安;据我的理解, var != "" 将首先被评估,然后如果为 true,那么另一部分将被评估,但这个概念似乎不起作用:)
如果 var 的值为 null,那么我将收到“nullreference”异常;这意味着 var != null 没有被评估。
请帮忙。
谢谢, 拉胡尔
Code Below:
if(var != "" && var.startswith("somestring"))
{ do something }
This code is troubling; as far as my understanding var != "" will be evaluated first and then if true then the other part will be evaluated but this concept is not working seems :)
If var is having a value null then I am getting an "nullreferrence" exception; which means
var != null is not getting evaluated.
Please Help.
Thanks,
Rahul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 C# 中,空字符串和空字符串之间存在区别。您必须检查所有 3 种情况,事实上,C# 包含针对这种情况的辅助方法:
In C#, there is a difference between a null string and an empty string. You have to check for all 3 cases, in fact, C# contains a helper method for just this case:
我认为您的意思是
null
而不是""
:PS:
var
是 C# 更高版本中的保留关键字。I think you meant
null
instead of""
:P.S.:
var
is a reserved keyword in later versions of C#.var != "" 与 var != null 不同。
var != "" is not the same as var != null.
"" 是一个有效的
字符串
- 它的长度恰好为 0。但它不是null
!要检查
null
,请编写var != null
。"" is a valid
string
- it just happens to have length 0. But it is notnull
!To check for a
null
, writevar != null
.如果您的变量有可能为空,则在尝试进行任何类型的处理(即使是简单的比较)之前,您需要检查它是否为空,否则您将收到此“nullreference”异常。
If there is ever a possibility that your variable will be null, you need to check if its null or not before you attempt to do any kind of processing (even a simple comparison), or you will get this "nullreference" exception.