c# - Is there a way to create a delegate to get and set values for a FieldInfo? -
for properties there getgetmethod
, getsetmethod
can do:
getter = (func<s, t>)delegate.createdelegate(typeof(func<s, t>), propertyinfo.getgetmethod());
and
setter = (action<s, t>)delegate.createdelegate(typeof(action<s, t>), propertyinfo.getsetmethod());
but how go fieldinfo
s?
i not looking delegates getvalue
, setvalue
(which means invoking reflection each time)
getter = s => (t)fieldinfo.getvalue(s); setter = (s, t) => (t)fieldinfo.setvalue(s, t);
but if there createdelegate
approach here? i mean since assignments return value, can treat assignments method? if there methodinfo
handle it? in other words how pass right methodinfo
of setting , getting value member field createdelegate
method delegate can read , write fields directly?
getter = (func<s, t>)delegate.createdelegate(typeof(func<s, t>), fieldinfo.??); setter = (action<s, t>)delegate.createdelegate(typeof(action<s, t>), fieldinfo.??);
i can build expression , compile it, looking simpler. in end don't mind going expression route if there no answer asked question, shown below:
var instexp = expression.parameter(typeof(s)); var fieldexp = expression.field(instexp, fieldinfo); getter = expression.lambda<func<s, t>>(fieldexp, instexp).compile(); if (!fieldinfo.isinitonly) { var valueexp = expression.parameter(typeof(t)); setter = expression.lambda<action<s, t>>(expression.assign(fieldexp, valueexp), instexp, valueexp).compile(); }
or after nonexistent (since have seen yet) ?
field access isn't performed via method (like getters , setters)--it's performed il instruction--so there's nothing can assign delegate. you'll have use expression route create "block" of code (effectively il) can assigned delegate.
Comments
Post a Comment