如何识别具有多个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;
}
答案 0 :(得分: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
扩展方法中 - 使其成为扩展方法意味着您也可以将其处理为null:
// ValidateAndLog returns true if everything is okay, false otherwise.
if (!emailNotificationData.ValidateAndLog())
{
return;
}
这样就不需要混淆其他代码了。
请注意,C#写作几乎没有任何好处:
if (null == x)
...除非您实际比较布尔值,否则优先进行常量优先比较的“正常”原因(捕捉=
的{{1}}的拼写错误)不适用,无论如何==
都不会编译。
答案 1 :(得分: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);
}
这通常会提高可读性。
答案 2 :(得分: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仅包含失败规则的消息。