2011-01-27 132 views
2
IndicationBase indication = new IndicationBase(Chatham.Web.UI.Extranet.SessionManager.PhysicalUser); 
// check for permissions 
LightDataObjectList<TransactionPermission> perms = indication.Model.Trx.TransactionPermissionCollection; 

所以有时indication将有一个Model.Trx.TransationPermissionCollection,很多时候它不会。在尝试访问它之前如何检查它是否发生,以免出现错误。c#使用前检查属性是否存在

回答

4

想必你得到一个NullReferenceException?不幸的是,这并没有很好的捷径。你必须做一些事情,如:

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

注意,酒店本身始终存在这里 - 静态类型,编译器确保这一点 - 它只是检查您是否已经在属性得到了非空引用随处可见的情况下,链。

当然,如果任一属性为非可空类型,你并不需要检查那些为无效:)

+0

有使用`dynamic`和/或表达式树的工作方式围绕这个问题......但是对于通常需要这种情况的少数情况来说,它们不够优雅而且过于复杂。 – LBushkin 2011-01-27 22:22:53