Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify anonymous methods in System.Reflection

How can you identify anonymous methods via reflection?

like image 775
devlife Avatar asked Mar 23 '10 20:03

devlife


3 Answers

Look at the attributes of the method, and see if the method is decorated with CompilerGeneratedAttribute.

Anonymous methods (as well as other objects, such as auto-implemented properties, etc) will have this attribute added.


For example, suppose you have a type for your class. The anonymous methods will be in:

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

This should return any anonymous methods defined on MyClass.

like image 169
Reed Copsey Avatar answered Oct 21 '22 00:10

Reed Copsey


You cannot, because there is no such thing as an anonymous method on IL level - they're all named, and all belong to named types. And the way C# and VB compilers translate anonymous methods to named methods and types is entirely implementation-defined, and cannot be relied on (which means that, for example, it can change with any update, even in minor releases / hotfixes).

like image 24
Pavel Minaev Avatar answered Oct 20 '22 23:10

Pavel Minaev


From what I can see, that Regex pattern would be:

<(\w|_)+>b_.+
like image 41
leppie Avatar answered Oct 21 '22 01:10

leppie