簡體   English   中英

通過反射找到特定的方法

[英]Finding a specific method via reflection

假設我們在一個類中有兩個公共方法:

public class SomeClass
{
    public bool DoSomething(int param1)
    {
        return param1 == 30;
    }

    public bool DoSomethingElse(int param1)
    {
        param1 *= 2;
        return param1 == 30;
    }
}

我可以編寫以下代碼來使用反射獲取這兩種方法:

MethodInfo[] methods = typeof(SomeClass).GetMethods(BindingFlags.Public | BindingFlags.Instance)
                       .Where(x => x.ReturnType == typeof(bool)
                              && x.GetParameters().Length == 1
                              && x.GetParameters()[0].ParameterType == typeof(int)).ToArray();

假設我只想要DoSomethingElse ,我可以只使用methods[1]

但是,假設它們在下次編譯此類時交換了位置。 我最終會選擇DoSomething

唯一將這兩種方法分開的是DoSomethingElse在檢查之前將參數乘以 2。

我可以用反射做任何其他檢查以確保我總是得到DoSomethingElse嗎?

注意:我正在尋找的方法可能會在每次編譯時更改其名稱,因此僅搜索它們的名稱也不起作用。

從技術上講,您可以分析方法的IL 代碼 讓我們檢查前10 IL 代碼中是否有* 2

https://en.wikipedia.org/wiki/List_of_CIL_instructions

代碼:

  MethodInfo[] methods = GetType()
    .GetMethods(BindingFlags.Public | BindingFlags.Instance)
    .Where(x => x.ReturnType == typeof(bool)
           && x.GetParameters().Length == 1
           && x.GetParameters()[0].ParameterType == typeof(int))
    .Where(m => m
       .GetMethodBody()
       .GetILAsByteArray()
       .Take(10)                  // take first 10 IL codes
       .SkipWhile(b => b != 0x18) // ldc.i4.2 : load 2
       .Any(b => b == 0x5A))      // mul      : multiply 
    .ToArray();

我們來看一下:

  Console.Write(string.Join(Environment.NewLine, methods.Select(m => m.Name)));

結果:

  DoSomethingElse

但是,我強烈建議使用特定的方法Name或使用屬性等標記方法。

暫無
暫無

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

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