简体   繁体   English

使用Reflection获得C#7.0中排除局部函数的方法?

[英]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: 到目前为止,我能想到的最好的方法是添加一个Where子句,该子句将过滤掉本地函数,例如:

    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: IsAssembly属性摘要:

Gets a value indicating whether the potential visibility of this method or constructor is described by System.Reflection.MethodAttributes.Assembly; 获取一个值,该值指示此方法或构造函数的潜在可见性是否由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. 也就是说,该方法或构造函数对于同一程序集中的其他类型最多是可见的,而对于程序集外部的派生类型则不可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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