Tipx
Tipx

Reputation: 7515

Extract a method's implementation with reflection

Lets say I have two classes, ClassA and ClassB as follow :

class ClassA
{
    public void MyFunctionA(ClassB classB)
    {
        classB.MyActionB = () => this.MySecretFunctionA(3); // "Hard coded 3"
    }

    private void MySecretFunctionA(int anInt)
    {
        Console.WriteLine(anInt.ToString());
    }
}

class ClassB
{
    public Action MyActionB;

    public void MyFunctionB()
    {
        MyActionB();
    }

    private void MySecretFunctionB()
    {
        // Here
    }
}

Is it possible for ClassB to "know" exactly, at runtime, what MyActionB will do when called? For example, is it possible for ClassB to extract "3", once again, at runtime? (see the "Hard coded 3" comment.)

ClassA and ClassB are in different assemblies, and if it makes a difference (I don't think so though) ClassB's assembly is loaded at runtime.

In the title, I suggested reflection, but if it's not the proper term in this circumstance, I'll edit it. If it is possible, just an idea of how would be nice. Thanks.

Upvotes: 0

Views: 84

Answers (1)

James Gaunt
James Gaunt

Reputation: 14793

You can get access to the IL for a method, via

http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getmethodbody(v=vs.90).aspx

However, whether this is any practical use depends on just how specific your use case is. There isn't a way to access or reverse engineer the syntax tree at runtime as this information isn't saved in the metadata.

Going forward perhaps something will be possible using the new Roslyn compiler, when it's released.

Upvotes: 1

Related Questions