加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:22:17 所属栏目:百科 来源:网络整理
导读:有没有办法使用反射来获取类中的私有静态方法,而无需在这些方法中定义任何本地函数? 例如,我有一个这样的类: public class Foo { private static void FooMethod(){ void LocalFoo(){ // do local stuff } // do foo stuff }} 如果我使用反射来抓取私有静
有没有办法使用反射来获取类中的私有静态方法,而无需在这些方法中定义任何本地函数?

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

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读