在 C# 中避免 NullReferenceException 的优雅方法 [英] Elegant way to avoid NullReferenceException in C#

查看:29
本文介绍了在 C# 中避免 NullReferenceException 的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做

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.

在没有三元组的情况下,有没有一种优雅的方法可以做到这一点?

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 不久前发布,它附带空值传播运算符 ?.,这将简化您的情况:

var path = HttpContext?.Current?.Request?.ApplicationPath

由于历史原因,可以在下面找到以前语言版本的答案.

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,则这将返回 null,否则返回 ApplicationPath.对于值类型,您必须在最后执行一次空检查.无论如何,到目前为止没有其他方法,除非您想在每个级别检查 null.

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); 
            }       
    }

这篇关于在 C# 中避免 NullReferenceException 的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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