深度空检查,有没有更好的方法?
- 作者: 一只被吓到的猫
- 来源: 51数据库
- 2022-10-20
问题描述
注意:这个问题是在引入 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 ?[].
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
