mercredi 19 août 2020

How could I extract the code of a method dynamically using reflection or something similar?

I've written a modular sandbox that is intended to be a living portfolio of sorts, and it's working great so far, but I had an idea for it that I can't seem to figure out how to do. As a quick overview, when I have a new idea, or want to test a new concept, I write a module for it. Each module derives from SandboxModule which contains an abstract method called Execute. When I create a module, it looks a little something like this:

public class DemoModule : SandboxModule {
    protected override void Execute() {
        // Do something super cool and new.
    }
}

There's nothing that prevents me from creating additional methods to call from the Execute method, just as I could in any other custom object:

public class DemoModule : SandboxModule {
    protected override void Execute() {
        int x = 3;
        SomethingSuperCoolAndNew(x);
    }
    private void SomethingSuperCoolAndNew(int someArg) {
        // Do something super cool and new.
    }
}

How do I capture the code contents of the Execute method, and any methods it may call, any they may call, etc, as a string, in a dynamic fashion, such as using reflection?


NOTES: I'm not against using third party libraries if I must. Though if it can be done without them, I'd prefer that route with respect to the nature of the sandbox.

I've already looked into using MethodBas.GetMethodBody(), it does not return what I'm wanting to display.

One idea that might work, would be to load the source file from my GitHub repo. I'll give that a try in the meantime, but I still wonder if there's a way to do it without jumping through that hoop?





Aucun commentaire:

Enregistrer un commentaire