编程语言
首页 > 编程语言> > 使用Reflection来获取排除C#7.0中本地函数的方法?

使用Reflection来获取排除C#7.0中本地函数的方法?

作者:互联网

有没有办法使用反射来获取类中的私有静态方法,而无需在这些方法中定义任何本地函数?

例如,我有一个这样的类:

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

如果我使用反射来抓取私有静态方法,如下所示:

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

然后我最终得到了类似的东西:

FooMethod
<FooMethod>g__LocalFoo5_0

使用gnarly编译器生成的本地函数名称.

到目前为止,我能够想到的最好的方法是添加一个Where子句来过滤掉本地函数,例如:

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

要么:

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

解决方法:

关于什么:

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

结果:

"FooMethod"

IsAssembly属性摘要:

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.

标签:c,reflection,c-7-0
来源: https://codeday.me/bug/20190705/1389857.html