jeudi 30 janvier 2020

Finding a specific method via reflection

Let's say we have two public methods within a class:

public class SomeClass
{
    public bool DoSomething(int param1)
    {
        return param1 == 30;
    }

    public bool DoSomethingElse(int param1)
    {
        param1 *= 2;
        return param1 == 30;
    }
}

I could write the following code to get both of these methods using reflection:

MethodInfo[] methods = typeof(SomeClass).GetMethods(BindingFlags.Public | BindingFlags.Instance)
                       .Where(x => x.ReturnType == typeof(bool)
                              && x.GetParameters().Length == 1
                              && x.GetParameters()[0].ParameterType == typeof(int)).ToArray();

Let's say I only wanted DoSomethingElse, I could just use methods[1].

However, let's say they swapped places the next time this class is compiled. I would end up with DoSomething instead.

The only thing that separates these two methods, is that DoSomethingElse multiplies the parameters by 2 before checking.

Are there any other checks I can do with reflection to ensure I always get DoSomethingElse?

Note: The methods I'm looking for may have their names changed each time it is compiled, so simply searching for their name won't work either.





Aucun commentaire:

Enregistrer un commentaire