mardi 11 octobre 2016

Change method call for specific object

Looking at this question got me wondering if something similar is possible using the dark reflection ways of C#.

Say I have this code:

public class Foo
    {
        public void FooPrint()
        {
            Console.Write("Foo");
        }
    }

public class Bar
{
    public Foo foo = new Foo();
    public Bar()
    {
        //do some reflection magic with member foo here ?
    }

    public void FooPrintRewritten()
    {
        Console.Write("Haha, only for Bar.foo."); 
    }
}

class Program
{
    static void Main(string[] args)
    {
        Foo a = new Foo();
        a.FooPrint(); // should still print "Foo"

        Bar bar = new Bar();
        bar.foo.FooPrint(); // should print "Haha, only for Bar.foo."
    }
}

Is what I ask for in the inlined comments in any way possible? Is there a way to re-bind a method call to another method for only a specific variable?

Yes I know this is ridiculous, no this shouldn't ever be used in production code. This is for the sake of curiosity.





Aucun commentaire:

Enregistrer un commentaire