2011-01-27 37 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