mercredi 15 novembre 2017

Use Reflection to get methods excluding local functions in C# 7.0?

Is there a way to use reflection to get private static methods in a class, without getting any local functions defined within those methods?

For instance, I have a class like so:

public class Foo {
    private static void FooMethod(){
        void LocalFoo(){
           // do local stuff
        }
        // do foo stuff
    }
}

If I use reflection to grab the private static methods like so:

var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
    .Select(m=>m.Name).ToList();

Then I end up with something like:

FooMethod
<FooMethod>g__LocalFoo5_0

With the gnarly compiler-generated name of the local function included.

So far, the best I have been able to come up with is to add a Where clause that would filter out the local functions, like:

    var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
        .Where(m=>!m.Name.Contains("<")
        .Select(m=>m.Name).ToList();

or:

    var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
        .Where(m=>!m.Name.Contains("__")
        .Select(m=>m.Name).ToList();





Aucun commentaire:

Enregistrer un commentaire