级联空引用异常检查? [英] Cascading null reference exception check?

查看:56
本文介绍了级联空引用异常检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在C#中进行一般的级联空引用检查?

Is there a way to do a generic cascading null reference check in c#?

我要实现的目标是,如果我尝试访问属于类C的字符串变量,而该类又是类B的一部分,而类B是A的类.

What i am trying to achieve is if i am trying to access a string variable which is part of a class C, which is inturn in class B, which is in A.

A.B.C.str

A.B.C.str

我通过了A,因此我必须检查A是否为空,然后检查B是否为空,然后检查C是否为空,然后访问str.

And that i am passed in A, i will have to check to see if A is null, then check if B is null, then check is C is null and then access str.

是否可以使用某些方法-我们可以传入A和A.B.C.str,如果一切正确存在,则返回null表示任何为null或str的值.

Is it possible to have some method where - we can potentially pass in, A and A.B.C.str and it return null is anything was null or value of str if everything existed correctly.

推荐答案

目前尚无内置方法可以执行此操作,但是在C#6.0中,我们希望使用安全导航"操作符,请参见杰里·尼克松(Jerry Nixon)的帖子

There is no built in way to do this yet, however in C# 6.0 we are expecting a 'safe navigation' operator, see this post by Jerry Nixon

它看起来像这样:

var g1 = parent?.child?.child?.child; 
if (g1 != null) // TODO

这篇关于级联空引用异常检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆