samedi 4 juillet 2015

Why does GetMethod need BindingFlags as mandatory information in order to find methods?

Assuming I have this class with a private method:

public class Test
{
    private void Method()
    {
    }
}

And this code:

var method1 = typeof(Test).GetMethod("Method"); // null
var method2 = typeof(Test).GetMethod("Method", BindingFlags.NonPublic | BindingFlags.Instance); // works!!
var method3 = typeof(Test).GetMethod("Method",BindingFlags.Instance); // null

  1. Why are method1 and method3 null?

  2. Why do I have to be specific with the BindingFlags in order to actually get the method?
    If it's because I can have multiple methods with the same name then what does the GetMethods exist for?

  3. How specific do I need to be? In this case I needed to add that I'm looking for a non-public & instance method. Since not all of the BindingFlags values are straight forward, how do I know where I need to stop?





Aucun commentaire:

Enregistrer un commentaire