public class NullResult
{
public bool Resulst
{ get; set; }
public string Message
{ get; set; }
}
{
public bool Resulst
{ get; set; }
public string Message
{ get; set; }
}
class MailConfig
{
public string MailFrom { get; set; }
public string MailTo { get; set; }
public string MailSubject { get; set; }
public string MailBody { get; set; }
public bool IsHtml { get; set; }
public NullResult ParmCheck(Expression<Func<MailConfig, string>> exp)
{
MemberExpression memberExp = exp.Body as MemberExpression;
string name = memberExp.Member.Name;
string temp = exp.Compile().Invoke(this);
if (string.IsNullOrEmpty(temp))
{
return new NullResult() { Resulst = false, Message = name + " is empty" };
}
return new NullResult() { Resulst = true };
}
public void Check()
{
List<NullResult> list = new List<NullResult>() { ParmCheck(it => it.MailFrom),ParmCheck(it=>it.MailTo),ParmCheck(it=>it.MailSubject), ParmCheck(it => it.MailBody) };
var query = list.Where(it => !it.Resulst);
if (query.Count() > 0)
{
throw new ArgumentException(string.Join(",",query.Select(it=>it.Message).ToArray()));
}
bool _isHtml = false;
bool.TryParse(settings["IsHtml"], out _isHtml);
IsHtml = _isHtml;
}
}
{
public string MailFrom { get; set; }
public string MailTo { get; set; }
public string MailSubject { get; set; }
public string MailBody { get; set; }
public bool IsHtml { get; set; }
public NullResult ParmCheck(Expression<Func<MailConfig, string>> exp)
{
MemberExpression memberExp = exp.Body as MemberExpression;
string name = memberExp.Member.Name;
string temp = exp.Compile().Invoke(this);
if (string.IsNullOrEmpty(temp))
{
return new NullResult() { Resulst = false, Message = name + " is empty" };
}
return new NullResult() { Resulst = true };
}
public void Check()
{
List<NullResult> list = new List<NullResult>() { ParmCheck(it => it.MailFrom),ParmCheck(it=>it.MailTo),ParmCheck(it=>it.MailSubject), ParmCheck(it => it.MailBody) };
var query = list.Where(it => !it.Resulst);
if (query.Count() > 0)
{
throw new ArgumentException(string.Join(",",query.Select(it=>it.Message).ToArray()));
}
bool _isHtml = false;
bool.TryParse(settings["IsHtml"], out _isHtml);
IsHtml = _isHtml;
}
}
假设我们有一个接口然后 我想对这个接口内部的属性进行一些验证是否有值了。 我们这次不想直接用Attribute标签的形式来进行验证。而是希望用lambda的形式来验证。
所以我们我构造了一个
ParmCheck 的方法可以允许我们的代码编写人员直接用lambda表达式的方式来过量行验证了。
ParmCheck(it => it.MailFrom);如果这个属性通不过验证。它就会直接报出这个这个属性通不过的消息了。
这样的好处是在我们如果重构了MailForm属性的时候 我们不需要去更改 字符串的信息