mercredi 14 avril 2021

Getting MethodInfo from a generated IEnumerator type

I'm trying to gather the attributes applied to an IEnumerator method based off an instance of the enumerator. For example:

static class Program {
    [SomeAttribute("Hello")]
    static IEnumerator Test() {
        yield return 1;
        yield return "x";
    }

    static void Main() {
        var foo = Test();
        // ... How to get the attribute from the 'foo' instance?
    }
}

foo.GetType() returns the generated type Program.<Test>d__4, so it seems to be somewhat aware of the method that generated it. How can I work backwards to find the MethodInfo of Test? From there I can get the attribute.

I also tried searching through the Program type, at each of it's methods' MethodInfo.ReturnType property to find one which returns Program.<Test>d__4. To my surprise, the MethodInfo I want just indicates a System.Collections.IEnumerator return type.

Maybe someone who understands the internals a little better can explain how I could get the MethodInfo from the generated type or vice versa.

Thanks.





Aucun commentaire:

Enregistrer un commentaire