2012 年 5 月,当您提出问题时,我没有看到比您提供的 try ... catch 更简单的解决方案。唯一的选择 - 使用“if”或“?”检查每个部分是否为空。看起来更丑(但可能更快一点)。
要么你必须写:
path = HttpContext!=null
? (HttpContext.Current!=null
? (HttpContext.Current.Request!=null
?(HttpContext.Current.Request.ApplicationPath!=null
? HttpContext.Current.Request.ApplicationPath
: null)
: null)
: null)
: null;
或者:
if (HttpContext == null || HttpContext.Current == null
|| HttpContext.Current.Request == null
|| HttpContext.Current.Request.ApplicationPath == null)
path = null;
else
path = HttpContext.Current.Request.ApplicationPath;
两者都在没有异常处理的情况下这样做。请注意,两者都使用“快捷方式”来中止检查是否找到任何空值。
更新(2017 年 12 月):
从C# 版本 6 及更高版本开始,您可以使用更好的解决方案,即所谓的Elvis
-Operator(也称为空合并运算符?.
和x?[i]
用于数组)。上面的例子
path = HttpContext!=null
? (HttpContext.Current!=null
? (HttpContext.Current.Request!=null
?(HttpContext.Current.Request.ApplicationPath!=null
? HttpContext.Current.Request.ApplicationPath
: null)
: null)
: null)
: null;
这样看起来好多了:
path = HttpContext?.Current?.Request?.ApplicationPath;
这完全一样,恕我直言,不仅仅是“只是”语法糖。结合附加的?? value
,您可以轻松地用null
其他值替换,例如
path = (HttpContext?.Current?.Request?.ApplicationPath) ?? "";
path
如果无法获得非空值,这会使变量为空。