0

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);
    }
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31

1 Answers1

0

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.

Ňuf
  • 6,027
  • 2
  • 23
  • 26
  • well i can see what you mean, but the setter in propertyInfo is seald and i cant think that those link could work. i would like something like this var user =Get() Now the user have implemented those changes without creating a new type in a new assy and so on. rihjt now im looking at Mono.Cecil and its good but it dose not support .net core 2 which is creazy – Alen.Toma Sep 29 '17 at 01:38