簡體   English   中英

如何在System.Reflection中識別匿名方法

[英]How to identify anonymous methods in System.Reflection

如何通過反射識別匿名方法?

查看方法的屬性,並查看該方法是否使用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());

這應該返回MyClass定義的任何匿名方法。

你不能,因為在IL級別上沒有匿名方法 - 它們都被命名,並且都屬於命名類型。 C#和VB編譯器將匿名方法轉換為命名方法和類型的方式完全是實現定義的,並且不能依賴(例如,它可以隨任何更新而更改,即使在次要版本/修補程序中也是如此)。

從我所看到的,正則表達式模式將是:

<(\w|_)+>b_.+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM