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