简体   繁体   中英

Dynamic Property setter c#

Hi guys I am trying to generate a delegate at runtime using Dynamic Methods and the ILGenerator to invoke the Setter of a property on an object.....

private static GenericIntSetter CreateIntSetMethod(PropertyInfo propertyInfo)
    {
        MethodInfo setMethod = propertyInfo.GetSetMethod();

        if (setMethod == null)
            return null;

        Type[] arguments = new Type[2];

        arguments[0] = typeof(Person);
        arguments[1] = typeof(int);

        DynamicMethod setter = new DynamicMethod(
             String.Concat("_Set", propertyInfo.Name, "_"),
             typeof(void), arguments, propertyInfo.DeclaringType);
        ILGenerator generator = setter.GetILGenerator();
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
        generator.Emit(OpCodes.Ldarg_1);

        if (propertyInfo.PropertyType.IsClass)
        {
            generator.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
        }
        else
        {
            generator.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
        }

        generator.EmitCall(OpCodes.Callvirt, setMethod, null);
        generator.Emit(OpCodes.Ret);

        return (GenericIntSetter)setter.CreateDelegate(typeof(GenericIntSetter));
    }

When I call this method and I invoke the delete I get a corrupt memory error, any ideas?

Yep. It's really complicated to do that, but not impossible.

I have a open source project just for that http://mirrormirror.codeplex.com

In http://mirrormirror.codeplex.com/SourceControl/changeset/view/66562#869731 you will find the code for all the emit I need to do. It should be easy to find the setter implementation.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM