c# - Set value of Expression<Func<T>> inside a function -
here part of complete argument validation system i've wrote validates user's given argument:
public void validate<t>(expression<func<t>> argexpr, bool justclean) t : icomparable, icomparable<t>, iconvertible, iequatable<t> { var expressionbody = (memberexpression)argexpr.body; var argname = expressionbody.member.name; var value = argexpr.compile().invoke(); if(!justclean) //check above value against invalid values , throw exception else //clean value , question: set member's value }
now need set expression's member value cleaned version of given value this:
validate(() => item.itemname, true);
as result expect item.itemname
has cleaned value set inside validate
method.
please notice can't return value function result, because of code flow. so, there way this?
you can generate setter expression base on expression sent function:
public static void validate<t>(expression<func<t>> argexpr, bool justclean) t : icomparable, icomparable<t>, iconvertible, iequatable<t> { var expressionbody = (memberexpression)argexpr.body; var argname = expressionbody.member.name; var value = argexpr.compile().invoke(); if (!justclean) { } else { var param = expression.parameter(typeof(t)); var setter = expression.lambda<action<t>>( expression.assign( expressionbody, param ), param ).compile(); setter(default(t)); // used default(t) example, can other t value } }
Comments
Post a Comment