簡體   English   中英

檢查對象的屬性為空

[英]Check properties of object is null

我有“相冊List ”對象(例如相冊)。 我檢查對象的屬性為null。

只是例子:

if (albums.Last() != null 
      && albums.Last().Photos != null 
      && albums.Last().Photos.Description != null) { //action }

我可以在代碼中縮短檢查時間嗎?

只需將其包裝在一個函數中:

public static bool IsInitialized(a Album) {
    return a != null &&
        a.Photos != null &&
        a.Photos.Description != null;
}

然后,您的調用代碼將變為:

var album = albums.LastOrDefault();

if (Album.IsInitialized(album)) {
    // its fine
}

你不能

順便說一句:

  1. 使用vars而不是一直都調用函數( Last() )。

  2. 使用LastOrDefault()並防止崩潰。

     var lastAlbum = albums.LastOrDefault(); if(lastAlbum != null && lastAlbum.Photos != null && lastAlbum.Photos.Description != null){//action} 

您可以使用擴展方法-

public static class ListExtension {
     public static bool IsLastPhotoNotNull(this List<Album> albums){
          var album = albums.LastOrDefault();
          return album != null && album.Photos != null && album.Photos.Description != null;
     }
}

然后用列表調用它

List<Album> albums;

if(!albums.IsLastPhotoNotNull()){
    //...do other actions
}

簡短一點 但是效率更高,是的。

您多次調用Last()方法。 如果該調用中涉及數據庫操作,則可能會損害性能。

將方法拉出if之外:

var last = albums.Last();
if (last != null 
  && last.Photos != null 
  && last.Photos.Description != null)
{ //action }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM