vendredi 15 novembre 2019

Using reflection to find an enumerator's method

Background:

I am modifying existing code using the Harmony Library. The existing C# code follows this structure:

public class ToModify
{
    public override void Update()
    {
        foreach (StatusItemGroup.Entry entry in collection)
        {
            // I am trying to alter an operation at the end of this loop.
        }
    }
}

public class StatusItemGroup
{
    public IEnumerator<Entry> GetEnumerator()
    {
        return items.GetEnumerator();
    }

    private List<Entry> items = new List<Entry>();

    public struct Entry { }
}

Due to the situation, I must modify the IL code that is being generated, to do so I must obtain the MethodInfo of my target operand. This is the target:

IL_12B6: callvirt  instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()

Question:

How do I obtain the MethodInfo for the MoveNext method of an enumerator?

What I've tried:

Everything I can think of has yielded null results. This is my most basic attempt:

MethodInfo targetMethod = typeof(IEnumerator<StatusItemGroup.Entry>).GetMethod("MoveNext");

I don't understand why this doesn't work, and I don't know what I need to do to correctly obtain the MethodInfo.





Aucun commentaire:

Enregistrer un commentaire