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

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

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

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

这通常会增加可读性。

您可以创建validation规则以检查emailNotificationData。

 public class Rule { public Func Test { get; set; } public string Message { get; set; } } 

然后,您将创建一个类,您可以在其中为emailNotificationData定义规则。

 public class EmailNotificationValidationRules { public static IEnumerable> Rules { get { return new List> { new Rule { Test = data => data != null, Message = "No email notifacation data" }, new Rule { Test = data => !string.IsNullOrEmpty(data.Sender), Message = "No sender" }, new Rule { 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仅包含失败规则的消息。