How can I get a link to the property setting tool?

I have asp.net code that populates fields in a LINQ to SQL object (all string fields) with values ​​from a published form:

            userSelections.A = Request.Form["A"];
            userSelections.B = Request.Form["B"];
            userSelections.C = Request.Form["C"];
            userSelections.D = Request.Form["D"];

I want to save the name of the form field and the associated setter in a table so that I can iterate through the whole set without having to write a bunch of repeating code.

Is there a way to get a delegate in the property adjuster? for example, I have a class myClass , with the string property myProperty . Can I get a delegate, something like void myPropertySetterDelegate (string val, MyClass this) , which can be used with any instance of the class?

I know that this can be done with reflection, but other developers of my project have performance problems, so I would prefer, if possible, a non-reflective solution.

Thank!

+5
source share
5 answers

you can use reflection to get information about the type you are trying to bind to the query, and then generate dynamic methods (you should cache them for reuse) to make execution very fast.

    public static Action<object, object> CreateSetter(FieldInfo field)
    {
        DynamicMethod dm = new DynamicMethod("DynamicSet", typeof(void),
            new Type[] { typeof(object), typeof(object) }, field.DeclaringType, true);

        ILGenerator generator = dm.GetILGenerator();

        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldarg_1);
        if (field.FieldType.IsValueType)
            generator.Emit(OpCodes.Unbox_Any, field.FieldType);
        generator.Emit(OpCodes.Stfld, field);
        generator.Emit(OpCodes.Ret);

        return (Action<object, object>)dm.CreateDelegate(typeof(Action<object, object>));
    }
+4
source

You can use lambda:

Action<MyClass, string> myPropertySetter = (mc, s) => mc.MyProperty = s;

And you have an instance MyClass:

MyClass something = repo.GetMyClass();
myPropertySetter(something, valueFromSomewhere);

Now, following your example:

Dictionary<string, Action<MyClass, string>> setters = new Dictionary<string, Action<MyClass, string>>();
setters.Add("A", Action<MyClass, string> myPropertySetter = (mc, s) => mc.A = s);
[...]

Further:

MyClass something = getFromSomewhere();
foreach (string key in Request.Form.Keys)
{
  setters[key](something, Request.Form[key]);
}
+6
source

:

Action<int> valueSetter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), tc, tc.GetType().GetProperty("Value").GetSetMethod());

, , . , "" " ". , Delegate , Type, Type . Delegate ?

+1
Action<string, MyClass> propertySetter = (val, @this) => { @this.Property = val; }
0

All Articles