内联asp.net代码中的NullReferenceException处理 [英] NullReferenceException handling in in-line asp.net code

查看:268
本文介绍了内联asp.net代码中的NullReferenceException处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行的aspx文件中有一些内联代码:

I have some inline code in an aspx file that executes:

<dd><%=  encode(Listing.Address.Line1) %> </dd>

问题是,在某些情况下,Listing对象将为null,因此对诸如Address之类的属性的引用将引发异常.我该如何处理该异常?我基本上想忽略它:捕获它,然后继续页面的常规执行/渲染.

Problem is, under certain circumstances the Listing object will be null and therefore references to properties such as Address will throw an exception. How do I handle that exception? I basically want to ignore it: catch it, and then proceed with regular execution/rendering of page.

推荐答案

进行空检查.测试您期望可能发生的异常的条件而不是处理它几乎总是更好的方法.与首先测试它并进行相应处理相比,运行时必须付出更多的工作来引发和处理异常.

Do a null check. It is almost always better to test for the conditions of an exception that you expect might happen rather than handle it. The runtime has to do more work to throw and handle an exception than it does to just test for it in the first place and deal with it accordingly.

<%= encode(Listing != null && Listing.Address != null ? Listing.Address.Line1 : string.Empty) %> 

并确保检查地址以防万一.短路是您的朋友,订购很重要.

And be sure to check address just in case. Short circuiting is your friend, the order matters in the &&ing.

如果没有更广阔的前景,我建议您的视图模型(如果有的话)具有一种自动为您执行此操作的方法.如果随处可见,这种东西在视图中会变得很丑陋.

Without seeing a broader picture, I would suggest that your viewmodel, if you have one, has a method that does this automatically for you. This kind of stuff gets ugly in the view if you have it everyplace.

这篇关于内联asp.net代码中的NullReferenceException处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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