vendredi 25 mai 2018

Override properties with reflection

I would like to override all properties with custom method calls using reflection.

The only way is by using PropertyBuilder and ILGenerator? I just found documentation about creating a new assembly and new class, but none about override a property in a defined class.

This is a sample class with int only properties.

public class Foo : MyContext
{
    public int Bar { get; set; }
    public int Baz { get; set; }
}

public class MyContext
{
    public MyContext()
    {
        var props = this.GetType().GetProperties();
        foreach(var p in props)
        {
            //...
        }
    }

    protected void CustomSet(string propName, int value)
    {
        //...
    }

    protected int CustomGet(string propName)
    {
        //...
    }
}

And that's de expected behaviour.

public class FooReflected : MyContext
{
    public int Bar 
    {
        get { return CustomGet("Bar"); }
        set { CustomSet("Bar", value); }
    }

    public int Baz
    {
        get { return CustomGet("Baz"); }
        set { CustomSet("Baz", value); }
    }
}





Aucun commentaire:

Enregistrer un commentaire