如何在具有多个OR条件的if语句中识别哪个条件失败?

Thi*_*a H 2 c#

如何在具有多个OR条件的if语句中识别哪个条件失败.示例如下.

if ((null == emailNotificationData || string.IsNullOrEmpty(emailNotificationData.Sender))
                        || null == emailNotificationData.ToRecipients)
  {
    LogProvider.Log(typeof(Notification), LogLevel.Error, "Error sending the email notification 'Here i want to log failed argument'");
    return;
  }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

没有重新检查每个条件,你不能.我只想把它写成:

if (emailNotificationData == null)
{
    // This is a helper method calling LogProvider.Log(...)
    LogEmailNotificationError("No email notification data");
    return;
}
if (string.IsNullOrEmpty(emailNotificationData.Sender))
{
    LogEmailNotificationError("No sender");
    return;
}
if (emailNotificationData.ToRecipients == null)
{
    LogEmailNotificationError("No recipients");
    return;
}
Run Code Online (Sandbox Code Playgroud)

您可以将此提取到ValidateAndLog通知数据类型的扩展方法中 - 使其成为扩展方法意味着您也可以将其处理为null:

// ValidateAndLog returns true if everything is okay, false otherwise.
if (!emailNotificationData.ValidateAndLog())
{
    return;
}
Run Code Online (Sandbox Code Playgroud)

这样就不需要混淆其他代码了.

请注意,编写C#几乎没有任何好处:

if (null == x)
Run Code Online (Sandbox Code Playgroud)

......除非你确实比较布尔值,"正常"的原因,宁愿恒一比较(捕捉的错字===)不适用,因为if (x = null)不会反正编译.

  • "尤达条件":) (2认同)

Tim*_*ter 7

使用多个if或有意义的bool变量:

bool noEmailData = emailNotificationData == null;
bool noEmailSender = string.IsNullOrEmpty(emailNotificationData.Sender);

if(noEmailData || noEmailSender)
{
    string msg = string.Format("Error sending the email notification: {0} {1}."
        , noEmailData ? "No email-data available" : ""
        , noEmailSender ? "No email-sender available" : "");
    LogProvider.Log(typeof(Notification), LogLevel.Error, msg);
}
Run Code Online (Sandbox Code Playgroud)

这通常会增加可读性.