一种获得深层价值的安全方法

时间:2019-05-29 21:48:23

标签: c#

假设我有一个很深的课,我需要在其中嵌入一些字段

int? result = this.child.button.data;
return result;

在任何时候,它都可能指向空值,在这种情况下,我也想返回空值。常见的方法是

if (this.child != null && this.child.button!= null) {
  return this.child.button.data;
} else {
  return null;
}

但是,如果该字段是真正的深层嵌套,那么我能想到的唯一解决方案是:

int? result = null;
try {
  result = this.child.button.handler.controller.renderer.data;
} catch (NullReferenceException ex) {
  // Do nothing here
}

这是正确的方法,还是有更好的解决方案?

1 个答案:

答案 0 :(得分:1)

您可以在C#-?中检查空条件运算符。 喜欢:

result = this?.child?.button?.handler?.controller?.renderer?.data;
相关问题