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

Viewed 844

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();
1 Answers

What about:

var methods = typeof(Foo).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
    .Where(x => !x.IsAssembly)
    .Select(x => x.Name)
    .ToList();

Result:

"FooMethod"

IsAssembly property summary:

Gets a value indicating whether the potential visibility of this method or constructor is described by System.Reflection.MethodAttributes.Assembly; that is, the method or constructor is visible at most to other types in the same assembly, and is not visible to derived types outside the assembly.

Related