简体   繁体   中英

System.Reflection.Emit adding code to propertyInfo

Im new to System.Reflection.Emit and trying to remove nuget PropertChanged.Fody from my library and build something similar. so here is what i got. this Method is called UpdateProperty bu what is really dose is overriding the PropertyInfo so if my PropertyInfo is not virtual this code wont work. so is it possible to only Update my PropertyInfo Set without creating a new Property ?

    private static void UpdateProperty(PropertyInfo propertyInfo, TypeBuilder typeBuilder, 
                                       MethodInfo raisePropertyChangedMethod)
    {
        // Update the setter of the class, here is the problem im creating new PropertyInfo
        PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyInfo.Name,
        PropertyAttributes.None, propertyInfo.PropertyType, null);

        // Create set method
        MethodBuilder builder = typeBuilder.DefineMethod("set_" + propertyInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual , null, new Type[] { propertyInfo.PropertyType });
        builder.DefineParameter(1, ParameterAttributes.None, "value");
        ILGenerator generator = builder.GetILGenerator();

        // Add IL code for set method
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldarg_1);
        generator.Emit(OpCodes.Call, propertyInfo.GetSetMethod());

        // Call property changed for object
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldstr, propertyInfo.Name);
        generator.Emit(OpCodes.Callvirt, raisePropertyChangedMethod);
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ret);
        propertyBuilder.SetSetMethod(builder);
    }

There is AFAIK no official way to replace method body (or property setter) at runtime (unless it is a dynamic method). There is number of ways how to do it anyway, though. See

But injecting code that raises PropertyChanged method when property value changes can be done at compile time (which is what PropertyChanged.Fody does) and it seems to me as preferable solution over runtime code modification.

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