2

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

3 回答 3

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

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

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

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

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

if (null == x)

...除非您实际上是在比较布尔值,否则首选常量优先比较的“正常”原因(捕获=for的拼写错误==)不适用,因为if (x = null)无论如何都不会编译。

于 2013-09-04T08:29:26.810 回答
7

使用多个ifs 或有意义的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);
}

这通常会增加可读性。

于 2013-09-04T08:34:02.213 回答
2

您可以创建验证规则来检查 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 仅包含失败规则的消息。

于 2013-09-04T09:31:20.303 回答