Is there such a thing as a chained NULL check?

前端 未结 7 465
灰色年华
灰色年华 2021-01-18 05:30

I have the following ugly code:

if (msg == null || 
    msg.Content == null || 
    msg.Content.AccountMarketMessage == null || 
    msg.Content.AccountMarke         


        
7条回答
  •  逝去的感伤
    2021-01-18 06:20

    There is no built-in support for this, but you can use an extension method for that:

    public static bool IsNull(this T source, string path)
    {
         var props = path.Split('.');
         var type = source.GetType();
    
         var currentObject = type.GetProperty(props[0]).GetValue(source);
    
         if (currentObject == null) return true;
         foreach (var prop in props.Skip(1))
         {
              currentObject = currentObject.GetType()
                    .GetProperty(prop)
                    .GetValue(currentObject);
    
             if (currentObject == null) return true;
         }
    
         return false;
    }
    

    Then call it:

    if ( !msg.IsNull("Content.AccountMarketMessage.Account.sObject") )  return;
    

提交回复
热议问题