我想做这个
var path = HttpContext.Current.Request.ApplicationPath;
如果沿途的任何属性为空,我希望路径为空,或者“”会更好。
有没有不用 Ternaries 的优雅方法?
理想情况下我会喜欢这种行为(没有可怕的表现和丑陋) 字符串路径;
try
{
path = HttpContext.Current.Request.ApplicationPath;
}
catch
{
path = null;
}
谢谢
最佳答案
[编辑]
C# 6 不久前发布,它附带空值传播运算符 ?.
,这会将您的情况简化为:
var path = HttpContext?.Current?.Request?.ApplicationPath
由于历史原因,可以在下面找到以前语言版本的答案。
我猜您正在寻找 Groovy 的安全取消引用运算符 ?.
,而您是 not the first.
从链接主题来看,我个人最喜欢的解决方案是 this one (that one 看起来也很不错)。
然后你可以这样做:
var path = HttpContext.IfNotNull(x => x.Current).IfNotNull(x => x.Request).IfNotNull(x => x.ApplicationPath);
您总是可以稍微缩短函数名称。如果表达式中的任何对象为 null,这将返回 null,否则返回 ApplicationPath。对于值类型,您必须在最后执行一次空检查。无论如何,到目前为止没有其他方法,除非您想在每个级别上检查 null。
这是上面使用的扩展方法:
public static class Extensions
{
// safe null-check.
public static TOut IfNotNull<TIn, TOut>(this TIn v, Func<TIn, TOut> f)
where TIn : class
where TOut: class
{
if (v == null) return null;
return f(v);
}
}
关于c# - 在 C# 中避免 NullReferenceException 的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815641/