XElement NullReferenceException
我有以下代码。
XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
现在,如果我返回的元素为 null,则会收到 NullReferenceException,因为 XElement 为 null。所以我将其更改为以下内容。
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
if(opCoOptOff != null)
{
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
我希望必须有一种更优雅的方法来执行此操作,因为这种情况经常出现,并且我希望避免每次出现问题时都进行此类检查。任何帮助将不胜感激
I have the following code.
XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
Now if the element I return is null, I am getting a NullReferenceException since the XElement is null. So I changed it to the following.
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
if(opCoOptOff != null)
{
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
I am hoping there has to be a more elegant way to do this since this scenario comes up often and I would like to avoid doing this type of check every time there is an issue. Any assistance would be greatly appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以编写
扩展方法
并使用它在任何地方:将其用作:
您也可以根据您的目的添加其他扩展。
编辑:我更新了答案,但如果您在我写之前仔细阅读它,您可以
根据您的目的添加其他扩展。
我写这个是因为我猜您可能想要调用 null 对象 Element,我不知道您的具体情况是什么,但我添加了一些代码以进行更多说明,根据您的情况完成 XDocumentExtension 类,并且注意扩展方法可以在 null 对象上工作。You can write an
extension method
and use it anywhere:Use it as :
Also you can add other extensions for your purpose.
Edit: I'd updated answer but if you read it carefully before I wrote you can
add other extensions for your purpose.
I wrote this because I guess you may be want to call on null objects Element, I don't know what's exact situation of yours but I add some code for more clarification, depend on your situation complete the XDocumentExtension class, and one note extension methods can work on null objects.实际上,您可以将 XElement 直接转换为字符串:
http://msdn.microsoft.com/en-us/library/bb155263.aspx
这样
可能是
You can actually cast the XElement directly to a string:
http://msdn.microsoft.com/en-us/library/bb155263.aspx
so
could be