如何在System.Reflection中识别匿名方法
如何通过reflection识别匿名方法?
查看方法的属性,并查看该方法是否使用CompilerGeneratedAttribute进行修饰。
匿名方法(以及其他对象,如自动实现的属性等)将添加此属性。
例如,假设您有一个类的类型。 匿名方法将在:
Type myClassType = typeof(MyClass); IEnumerable anonymousMethods = myClassType .GetMethods( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) .Where(method => method.GetCustomAttributes(typeof(CompilerGeneratedAttribute)).Any());
这应该返回MyClass
定义的任何匿名方法。
你不能,因为在IL级别上没有匿名方法这样的东西 – 它们都被命名,并且都属于命名类型。 C#和VB编译器将匿名方法转换为命名方法和类型的方式完全是实现定义的,并且不能依赖(例如,它可以随任何更新而更改,即使在次要版本/修补程序中也是如此)。
从我所看到的,正则表达式模式将是:
<(\w|_)+>b_.+