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

本文关键字:条件 语句 if 失败 识别 OR | 更新日期: 2023-09-27 18:30:04

如何识别具有多个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;
  }

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

如果不重新检查每个条件,就不能。我只想写为:

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;
}

不过,您可以将其提取到通知数据类型的ValidateAndLog扩展方法中——将其作为扩展方法意味着您也可以处理其为null:

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

这样就不需要打乱其他代码。

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

if (null == x)

除非您实际在比较布尔值,否则首选常量优先比较的"正常"原因(发现===拼写错误)并不适用,因为if (x = null)无论如何都不会编译。

使用多个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);
}

这总体上提高了可读性。

您可以创建一个验证规则来检查emailNotificationData。

public class Rule<T>
{
    public Func<T, bool> Test { get; set; }
    public string Message { get; set; }
}

然后创建一个类,在其中定义emailNotificationData的规则。

public class EmailNotificationValidationRules
{
    public static IEnumerable<Rule<EmailNotificationData>> Rules 
    {
        get
        {
            return new List<Rule<EmailNotificationData>>
                {
                    new Rule<EmailNotificationData> { Test = data => data != null, Message = "No email notifacation data" },
                    new Rule<EmailNotificationData> { Test = data => !string.IsNullOrEmpty(data.Sender), Message = "No sender" },
                    new Rule<EmailNotificationData> { Test = data => data.ToRecipients != null, Message = "No recipients" }
                };
        }
    }
}

现在你可以用这个代码检查你的物体

        bool isValid = EmailNotificationValidationRules.Rules.All(rule => rule.Test(emailNotificationData));
        if (isValid == false)
        {
            var failedRules = EmailNotificationValidationRules.Rules.Where(rule => rule.Test(emailNotificationData) == false);
            var text2Log = failedRules.Aggregate(new StringBuilder(), (builder, rule) => builder.AppendLine(rule.Message), builder => builder.ToString());
        }

字段text2log仅包含失败规则的消息。