深空检查,有没有更好的办法? [英] Deep null checking, is there a better way?

查看:107
本文介绍了深空检查,有没有更好的办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意::此问题是引进运算符在C#6 /的Visual Studio 2015年。

Note: This question was asked before the introduction of the .? operator in C# 6 / Visual Studio 2015.

我们都在那里,我们有一些深物业类似cake.frosting.berries.loader,我们需要检查它是否是空,因此没有例外。做的方法是是使用短路if语句

We've all been there, we have some deep property like cake.frosting.berries.loader that we need to check if it's null so there's no exception. The way to do is is to use a short-circuiting if statement

if (cake != null && cake.frosting != null && cake.frosting.berries != null) ...

这给我的印象却是不是很优雅,但也许应该检查整个链条,看看它是否碰到一个空的变量/属性的更简单的方法。

This strikes me however as not very elegant, there should perhaps be an easier way to check the entire chain and see if it comes up against a null variable/property.

那么,使用它可能有些扩展方法或者这将是一个语言特性,还是仅仅是一个坏主意?

So is it possible using some extension method or would it be a language feature, or is it just a bad idea?

推荐答案

我们已考虑加入新的操作?。到拥有你想要的语义的语言。 (它已经现在增加;见下文)这就是说,你会说

We have considered adding a new operation "?." to the language that has the semantics you want. (And it has been added now; see below.) That is, you'd say

cake?.frosting?.berries?.loader

和编译器会生成所有短路检查你。

and the compiler would generate all the short-circuiting checks for you.

它没有为C#4条也许对于语言的假想未来版本。

It didn't make the bar for C# 4. Perhaps for a hypothetical future version of the language.

更新(2014):
 在运营商现在是<一个href=\"https://roslyn.$c$cplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Documentation\">planned在接下来的罗斯林编译器版本。需要注意的是仍然有在运营商的确切句法和语义分析的一些争论。

Update (2014): The ?. operator is now planned for the next Roslyn compiler release. Note that there is still some debate over the exact syntactic and semantic analysis of the operator.

更新(2015年7月):的Visual Studio 2015年已被释放,并附带支持的空条件运算符?[]

Update (July 2015): Visual Studio 2015 has been released and ships with a C# compiler that supports the null-conditional operators ?. and ?[].

这篇关于深空检查,有没有更好的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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