简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM