深度空检查,有没有更好的方法?

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

问题描述

注意:这个问题是在引入 C# 6/Visual Studio 2015 中的 .? 运算符.

我们都去过那里,我们有一些像 cake.frosting.berries.loader 这样的深层属性,我们需要检查它是否为空,所以没有例外.做的方法是使用短路if语句

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

这不是很优雅,也许应该有一种更简单的方法来检查整个链,看看它是否遇到空变量/属性.

是否可以使用某种扩展方法,或者它是一种语言功能,还是只是一个坏主意?

解决方案

我们已经考虑添加一个新的操作?".到具有您想要的语义的语言.(现在已经添加了;见下文.)也就是说,你会说

cake?.frosting?.berries?.loader

编译器会为你生成所有的短路检查.

它没有成为 C# 4 的标准.也许是该语言的假设未来版本.

更新(2014 年):?. 运算符现在已计划 用于下一个 Roslyn 编译器版本.请注意,关于运算符的确切句法和语义分析仍存在一些争论.

更新(2015 年 7 月):Visual Studio 2015 已发布并附带支持 空条件运算符 ?.?[].>

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

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 is not exactly elegant, and there should perhaps be an easier way to check the entire chain and see if it comes up against a null variable/property.

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.

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

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.

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

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

上一条:Nullable<T>.HasValue 或 Nullable<T> 之间有什么区别?!= 空? 下一条:“x 为空"和“x 为空"有什么区别?和“x == null"?

相关文章

最新文章