是否可以检查对象是否为null和值ONE? [英] Can I check a object against null and a value in ONE if?

查看:82
本文介绍了是否可以检查对象是否为null和值ONE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我收到XML代码,并想检查我的元素之一是否包含属性"nil".如果是,我要检查"nil"是否为"true".

当然可以写:

For example, I receive XML code and want to check if one of my elements contains the attribute "nil". If it does, i want to check if "nil" is "true.

For sure i can write:

if(xml.Element("page").Attribute("nil") != null)
  if(xml.Element("page").Attribute("nil").Value != "true" )
    //carry on here



但是,有没有一种方法可以在一个if语句中编写相同的内容?

像工作中的



But is there a way to write the same in ONE if-statement?

Like a working

if(xml.Element("page").Attribute("nil") != null && xml.Element("page").Attribute("nil").Value != "true")


以便在if语句中的第一个表达式为false时中断"?

预先感谢,
Markus


so that it "breaks" after the first expression in the if-statement if it is false?

Thanks in advance,
Markus

推荐答案

是的-您拥有的代码将做到这一点.
C#条件被指定为从左到右进行求值,因此只要您将null检查作为第一个条件,您就可以了,因为如果求值失败,求​​值将停止(因为整个&&"子句将自动为false,所以没有继续的意义.

我经常写:
Yes - the code you have will do that.
C# conditions are specified to be evaluated left-to-right, so provided your null check is the first condition, you are fine because evaluation will stop if it fails (as the whole "&&" clause will automatically be false, so there is no point in continuing).

I often write:
if (obj != null && obj.Value)
   {
   }


这篇关于是否可以检查对象是否为null和值ONE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆