问题描述
我想这样做
var path = HttpContext.Current.Request.ApplicationPath;
如果任何沿途的属性是空的,我想成为空路径,或会更好。
If any of the Properties along the way is null, i want path to be null, or "" would be better.
有一种优雅的方式来做到这一点没有Ternaries?
Is there an elegant way to do this without Ternaries?
我非常希望这种行为(不可怕的性能和丑)字符串的路径;
ideally i would like this behavior (without the horrible performance and ugliness)string path;
try
{
path = HttpContext.Current.Request.ApplicationPath;
}
catch
{
path = null;
}
感谢您
推荐答案
C#6得到了前一段时间发布的,并与空传播运营商
,这将简化你的情况来运:?
C# 6 got released a while ago and it shipped with null-propagating operator ?.
, which would simplify your case to:
var path = HttpContext?.Current?.Request?.ApplicationPath
由于历史的原因,为previous语言版本的答案可以在下面找到。
For historical reasons, answer for previous language versions can be found below.
我猜你正在寻找Groovy的安全对其操作?
,而你的从链接的话题,解决方案,我个人最喜欢的是这个(的看起来相当不错太)。然后,你可以这样做:
I guess you're looking for Groovy's safe dereferencing operator ?.
, and you're not the first.From the linked topic, the solution I personally like best is this one (that one looks quite nice too).Then you can just do:
var path = HttpContext.IfNotNull(x => x.Current).IfNotNull(x => x.Request).IfNotNull(x => x.ApplicationPath);
您可以随时缩短函数名一点点。这将返回null如果有的话在EX pression对象为空,ApplicationPath不然。对于值类型,你必须在年底进行一次零检查。无论如何,有没有其他办法,到目前为止,除非你想核对空的各个层面。
You can always shorten the function name a little bit. This will return null if any of the objects in the expression is null, ApplicationPath otherwise. For value types, you'd have to perform one null check at the end. Anyway, there's no other way so far, unless you want to check against null on every level.
下面是上面使用的扩展方法:
Here's the extension method used above:
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);
}
}
这篇关于优雅的方式来避免的NullReferenceException在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!