繁体   English   中英

c#在使用之前检查属性是否存在

[英]c# check if property exists before using it

IndicationBase indication = new IndicationBase(Chatham.Web.UI.Extranet.SessionManager.PhysicalUser);
// check for permissions
LightDataObjectList<TransactionPermission> perms = indication.Model.Trx.TransactionPermissionCollection;

因此,有时indication会具有Model.Trx.TransationPermissionCollection ,但很多时候却不会。 在尝试访问它之前,我该如何检查它是否起作用,这样我就不会收到错误消息。

想必您会收到NullReferenceException吗? 不幸的是,这没有很好的捷径。 您必须执行以下操作:

if (indication.Model != null &&
    indication.Model.Trx != null)
{
    var perms = indication.Model.Trx.TransactionPermissionCollection;
    // Use perms (which may itself be null)
}

请注意,属性本身始终存在于此-静态类型化和编译器确保了这一点-这只是检查属性链中是否到处都有非null引用的一种情况。

当然,如果任何属性都是不可为null的类型,则无需检查它们是否为null :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM