Ree*_*sey 8

查看方法的属性,并查看该方法是否使用CompilerGeneratedAttribute进行修饰.

匿名方法(以及其他对象,如自动实现的属性等)将添加此属性.


例如,假设您有一个类的类型.匿名方法将在:

Type myClassType = typeof(MyClass);
IEnumerable<MethodInfo> anonymousMethods = myClassType
    .GetMethods(
          BindingFlags.NonPublic
        | BindingFlags.Public 
        | BindingFlags.Instance 
        | BindingFlags.Static)
    .Where(method => 
          method.GetCustomAttributes(typeof(CompilerGeneratedAttribute)).Any());
Run Code Online (Sandbox Code Playgroud)

这应该返回任何定义的匿名方法MyClass.


Pav*_*aev 8

你不能,因为在IL级别上没有匿名方法这样的东西 - 它们都被命名,并且都属于命名类型.C#和VB编译器将匿名方法转换为命名方法和类型的方式完全是实现定义的,并且不能依赖(例如,它可以随任何更新而更改,即使在次要版本/修补程序中也是如此).

  • +1:从技术上讲,这是"正确"的答案 - 但[CompilerGenerated]在实践中相当可靠. (3认同)

lep*_*pie 5

从我所看到的,正则表达式模式将是:

<(\w|_)+>b_.+
Run Code Online (Sandbox Code Playgroud)