i new c# , lambda expressions; in this tutorial cannot understand code lambda expression:
public viewmodel() { base.addrule(() => aid, () => aid.length >= (5 * 2) && aid.length <= (16 * 2) && aid.length % 2 == 0, "invalid aid."); } and addrule method tutorial says adds rule rule dictionary:
public void addrule<t>(expression<func<t>> expression, func<bool> ruledelegate, string errormessage) { var name = getpropertyname(expression); rulemap.add(name, new binder(ruledelegate, errormessage)); } and
protected static string getpropertyname<t>(expression<func<t>> expression) { if (expression == null) throw new argumentnullexception("expression"); expression body = expression.body; memberexpression memberexpression = body memberexpression; if (memberexpression == null) { memberexpression = (memberexpression)((unaryexpression)body).operand; } return memberexpression.member.name; } } what () => aid mean , why addrule receives , cast unaryexpression , memberexpression ?
() => aid shorthand () => { return aid; }, returns property (or field - didn't show declaration). results in anonymous function.
but because addrule method takes expression<func<t>> instead of func<t>, compiler creates instructions create ast (abstract syntax tree) instead of anonymous function. ast can compiled method, here it's used extract name of property/field.
the alternative pass property name string. advantage of using member expression it's refactor-friendly: renaming property update code, ensuring rule still associated right property.
this being passed addrule (you can manually, you'd lose refactor-friendly benefit - besides, () => aid lot more concise):
expression.lambda<func<t>>( expression.property( expression.constant(this), "aid"));
Comments
Post a Comment