我使用了很多的出口在不同的班级在我的项目数据库中的数据。例如,我有
I am using a lot of database data in my project that is exported in different classes. For example, I have
transaction.Layout.Multimedia.Images.first();
的问题是,这些性质不一定可用
The problem is that these properties are not necessarily available.
因此,它可能是 transaction.Layout
为空,则可能是 transaction.Layout.Multimedia
为空,等等。
So, it is possible that transaction.Layout
is null, it is possible that transaction.Layout.Multimedia
is null, and so on.
我目前使用的每一个属性:
I currently use this for every property:
if (transaction.Layout != null)
{
if (transaction.Layout.Multimedia != null)
{
if (transaction.Layout.Multimedia.Images != null)
{
if (transaction.Layout.Multimedia.Images.count > 0)
{
var img = transaction.Layout.Multimedia.Images.first();
}
}
}
}
我想知道是否有更好的办法,我可以检查所有父类,以确保我所需要的属性是可用的。这些都不是我使用的唯一对象,也有其他人也有完全不同的名字。
I was wondering if there is a better way that I can check all parent classes to make sure that the property I need is available. These aren't the only objects I use, there are others as well with totally different names.
在此先感谢
没有,没有的但的。 .NET(罗斯林)的新版本具有的空传播运营商
No, there is not yet. The new version of .NET (Roslyn) has the Null propagating operator.
然后,你可以这样做:
if (transaction?.Layout?.Multimedia?.Image?.count > 0)
{
var img = transaction.Layout.Multimedia.Images.first();
}
目前,我们坚持这一点。你可以最大限度地减少需要通过连接检查,像这样的行:
For now, we are stuck with this. You could minimize the rows needed by concatenating the checks, like this:
if ( transaction.Layout != null
&& transaction.Layout.Multimedia != null
&& transaction.Layout.Multimedia.Images != null
&& transaction.Layout.Multimedia.Images.count > 0
)
{
var img = transaction.Layout.Multimedia.Images.first();
}
没有什么更多的事情要做。
There is nothing more to do.