c# - 在 C# 中避免 NullReferenceException 的优雅方法

标签 c# .net syntax web

我想做这个

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/

相关文章:

c# - 当文本很长且换行时,gridview 边界字段宽度不受控制

c# - 在 OnMessageOptions 中使用 ExceptionReceived

c# - .NET 中的动态 WSDL 位置

c - 如何使用 printf 格式化 unsigned long long int?

google-sheets - Col BY 在 Google 表格查询中导致解析错误

c# - 如何使用身份在 MVC 5 中自定义用户表?

c# - MongoDB C# - 为不存在的元素获取 BsonDocument

javascript - 如何在重定向后立即执行 JavaScript 操作?

c# - 如何使用 C# 淡入/淡出包含内容的面板

c - C 中的对象 - 结构体语法相关