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

Is there a way to use reflection to get private static methods in a class without any local functions defined in these methods?

For example, I have a class:

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

If I use reflection to capture private static methods as follows:

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

Then I get something like:

FooMethod
<FooMethod>g__LocalFoo5_0

With gnarly compiler-generated local function name.

So far, the best I've been able to come up with is to add a Where clause that will filter out local functions, for example:

    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();
+4
source share
1 answer

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:

, , System.Reflection.MethodAttributes.Assembly; .

+1

Source: https://habr.com/ru/post/1689352/


All Articles