处理可能包含空值的属性链
我有一些代码在长属性链的末尾提取一个值,其中任何一个属性都可能为空。
例如:
var value = prop1.prop2.prop3.prop4;
为了处理 prop1 中 null 的可能性,我必须写:
var value = prop1 == null ? null : prop1.prop2.prop3.prop4;
为了处理 prop1 和 prop2 中 null 的可能性,我必须写:
var value = prop1 == null
? null
: prop1.prop2 == null ? null : prop1.prop2.prop3.prop4;
或
var value = prop1 != null && prop1.prop2 != null
? prop1.prop2.prop3.prop4
: null;
如果我想处理这种可能性如果 prop1、prop2 和 prop3 中也存在 null,甚至更长的属性链,那么代码就会开始变得非常疯狂。
必须有更好的方法来做到这一点。
如何处理属性链,以便在遇到 null 时返回 null?
像 ?? 这样的东西运营商会很棒。
I have some code that is extracting a value at the end of a long property chain where any one of the properties could be null.
For example:
var value = prop1.prop2.prop3.prop4;
In order to handle the possibility of null in prop1 I have to write:
var value = prop1 == null ? null : prop1.prop2.prop3.prop4;
In order to handle the possibility of null in prop1 and prop2 I have to write:
var value = prop1 == null
? null
: prop1.prop2 == null ? null : prop1.prop2.prop3.prop4;
or
var value = prop1 != null && prop1.prop2 != null
? prop1.prop2.prop3.prop4
: null;
If I want to handle the possibility of null in prop1, prop2 and prop3 as well, or even longer property chains, then the code starts getting pretty crazy.
There must be a better way to do this.
How can I handle property chains so that when a null is encountered, null is returned?
Something like the ?? operator would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新
从 C# 6 开始,解决方案现已融入到该语言中 空条件运算符;
?.
用于属性,?[n]
用于索引器。旧答案
我查看了那里的不同解决方案。其中一些使用将多个扩展方法调用链接在一起,我不喜欢这种做法,因为由于每个链添加的噪音量,它的可读性不太好。
我决定使用仅涉及单个扩展方法调用的解决方案,因为它更具可读性。我还没有测试性能,但就我而言,可读性比性能更重要。
我创建了以下类,松散地基于 此解决方案
这允许我编写以下内容:
x
将包含scholarshipApplication.Scholarship.CostScholarship.OfficialCurrentWorldRanking
或的值null
如果链中的任何属性一路返回 null。Update
As of C# 6, a solution is now baked into the language with the null-conditional operator;
?.
for properties and?[n]
for indexers.Old Answer
I had a look at the different solutions out there. Some of them used chaining multiple extension method calls together which I didn't like because it wasn't very readable due to the amount of noise added for each chain.
I decided to use a solution that involved just a single extension method call because it is much more readable. I haven't tested for performance, but in my case readability is more important than performance.
I created the following class, based loosely on this solution
This allows me to write the following:
x
will contain the value ofscholarshipApplication.Scholarship.CostScholarship.OfficialCurrentWorldRanking
ornull
if any of the properties in the chains return null along the way.我使用 IfNotNull 扩展方法 来处理这个问题。
它不是世界上最漂亮的东西(如果我看到它有 4 层深,我会有点害怕),但它适用于较小的情况。
I use an IfNotNull extension method to deal with this.
It's not the prettiest thing in the world (I'd be a bit scared if I saw it going 4 layers deep) but it works for the smaller cases.