close
如果想知道程式碼裡引用了哪些類別、哪些函式,用一般的 reflection 方法似乎不管用。後來在網路上找到了這篇:
http://stackoverflow.com/questions/5490025/c-sharp-reflection-and-find-all-references
這篇文章提供了一個方法,後來就把MethodBaseRocks.cs這支程式抓回來用,效果不錯。
假設現在有一個類別:
public class TestClass { public void Test() { int a = 1; a += 1; string str = "test"; Console.WriteLine(a); Console.WriteLine(str); } }
現在要知道 Test 這個 method 呼叫了哪些函式,方法如下:
MethodBase methodBase = typeof(TestClass).GetMethod("Test"); var instructions = MethodBodyReader.GetInstructions(methodBase); foreach (Instruction instruction in instructions) { MethodInfo methodInfo = instruction.Operand as MethodInfo; if (methodInfo != null) { Type type = methodInfo.DeclaringType; ParameterInfo[] parameters = methodInfo.GetParameters(); Console.WriteLine("{0}.{1}({2});", type.FullName, methodInfo.Name, String.Join(", ", parameters.Select(p => p.ParameterType.FullName + " " + p.Name).ToArray()) ); } }
執行結果
全站熱搜