jeudi 9 juillet 2020

Can you use reflection to get the LocalVariables in an async method?

I am trying to write a method that will programatically generate documentation about where certain types are used in an application. I am trying to use reflection to determine which methods create instances of these types. This works fine for regular methods, for example:

class Program
{
    static void Main(string[] args)
    {
        var program = typeof(Program);
        
        var variablesTestMethod = program.GetMethod("VariablesTest").GetMethodBody().LocalVariables;

        Console.ReadLine();
    }

    public void VariablesTest()
    {
        var firstVariable = "First Variable";
        var secondVariable = 10;
    }
}

In this instance, variablesTestMethodLocalVariables is a list that contains 2 items, System.String and System.Int32, which is what I would expect. However, if the method is marked as async, this does not work.

class Program
{
    static void Main(string[] args)
    {
        var program = typeof(Program);

        var asyncVariablesTestMethod = program.GetMethod("AsyncVariablesTest").GetMethodBody().LocalVariables;

        Console.ReadLine();
    }

    public async Task AsyncVariablesTest()
    {
        var firstVariable = "First Variable";
        var secondVariable = 10;
    }
}

In this case, instead of a list containing the two variables, there is just one variable, and the type is listed as LocalVariablesTest.Program+<AsyncVariablesTest>d__2, which is not what I need.

Is there any way to determine the types referenced in an asynchronous method by using the LocalVariables property on the method body? Or is there another method or library that I could use to get what I need?





Aucun commentaire:

Enregistrer un commentaire