是否有一种方便的语法来检查可以为空的嵌套属性?
可能的重复:
深度空检查,有更好的方法吗?
例如,如果您正在 Foo1.Bar1.Foo2.Bar2 上执行逻辑(并且每个属性都可以为 null),则不能只对 foo.Bar1.Foo2.Bar2 执行此操作,因为您可能会得到 null参考异常
目前这就是我所做的
if (foo1!=null && foo1.Bar1!=null && foo1.Bar1.Foo2 !=null && foo1.Bar1.Foo2.Bar2!=null)
return DoStuff(foo1.Bar1.Foo2.Bar2); //actually a logic based on the value of Bar2
else return null;
有没有更优雅或更方便的方法来做到这一点?
Possible Duplicate:
Deep Null checking, is there a better way?
for example, if you are performing a logic on Foo1.Bar1.Foo2.Bar2 (and each of the properties can be null), you can't just do that to foo.Bar1.Foo2.Bar2 because it is possible that you get null reference exception
Currently this is what I do
if (foo1!=null && foo1.Bar1!=null && foo1.Bar1.Foo2 !=null && foo1.Bar1.Foo2.Bar2!=null)
return DoStuff(foo1.Bar1.Foo2.Bar2); //actually a logic based on the value of Bar2
else return null;
Is there a more elegant or convenient way, to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不幸的是没有。我也经常希望有一个更简单的语法!
然而,我想出了一个相当不错的替代方案:创建一个空安全链辅助方法。它看起来像这样:
这是方法:
我还创建了一堆重载(带有 2 到 6 个参数)。这对我来说真的很有效!
No, unfortunately there isn't. I too have often wished for a simpler syntax!
However, here's a pretty decent alternative that I came up with: create an Null-Safe-Chain helper method. Here's what it looks like:
Here's the method:
I also created a bunch of overloads (with 2 to 6 parameters). This works really well for me!
这个扩展方法有效,但不是很酷的代码,或者可能可以改进它:
使用它:
this extention method work but is not cool code or may be can improve it:
use it:
不,没有。
唯一可能有帮助的是评估
DoStuff
是否确实在正确的类中定义。No, there isn't.
The only thing that might help, is to evaluate if
DoStuff
is actually defined in the right class.