【问题标题】:Check properties of object is null检查对象的属性是否为空
【发布时间】:2014-08-22 19:05:09
【问题描述】:

我有List 的相册对象(例如相册)。我检查对象的属性是否为空。

举例:

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

我可以用更短的代码来做这个检查吗?

【问题讨论】:

  • 等待下一个 c# 版本。现在你不能
  • C# 是语言而不是魔法
  • 您可以结合使用表达式和反射 - 这是我的完整代码 stackoverflow.com/questions/429112/…
  • try { //action } catch (NullReferenceException){} 怎么样?我想忽略异常不是好习惯?
  • @derape:你现在不希望这样简单的异常处理开销。

标签: c# .net


【解决方案1】:

只需将其包装在一个函数中:

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
}

【讨论】:

    【解决方案2】:

    你不能。

    顺便说一句:

    1. 使用 vars 而不是一直调用函数 (Last())。

    2. 使用LastOrDefault() 并防止崩溃。

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

    【讨论】:

      【解决方案3】:

      您可以使用扩展方法 -

      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
      }
      

      【讨论】:

        【解决方案4】:

        更短,不。但是更有效率,是的。

        您多次调用Last() 方法。例如,如果该调用涉及数据库操作,则可能会损害性能。

        拉到if之外的方法:

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

        【讨论】:

          猜你喜欢
          • 2020-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-07
          • 1970-01-01
          • 2014-05-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多