为什么一个可以测试空返回,但另一个会抛出异常?
我想测试 xml 属性是否存在。鉴于此:
XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes;
第一个测试有效:
if (null != PG_attrColl["SomeAttribute"])
“GetNamedItem”应该返回 null,但以下测试抛出一个异常,抱怨它返回的 null。
if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)
为什么有区别?只是好奇。
I want to test if an xml attribute is present. Given this:
XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes;
This first test works:
if (null != PG_attrColl["SomeAttribute"])
"GetNamedItem" is supposed to return null, but the following test throws an exception complaining about the null it returns.
if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)
Why the difference? Just curious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为如果
GetNamedItem
返回 null,则无法调用其Value
成员。或者
Because if
GetNamedItem
has returned null, you can't call for itsValue
member.Or
if (null != PG_attrColl["SomeAttribute"])
此处检查属性是否为 null
if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)
这里您要检查属性的值是否为空。该代码首先尝试访问该属性,该属性为空,引发异常。
if (null != PG_attrColl["SomeAttribute"])
Here you are checking to see if the Attribute is null
if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)
Here you are checking to see if the Value of the attribute is null. The code is trying to access the attribute first, which is null, throwing an exception.