2017-01-17 11 views
3

特定の関数を呼び出す関数のリストを取得する:C#これは、この質問への接線の一種である

Retrieving the calling method name from within a method

public Main() 
{ 
    PopularMethod(); 
} 

public ButtonClick(object sender, EventArgs e) 
{ 
    PopularMethod(); 
} 

public Button2Click(object sender, EventArgs e) 
{ 
    PopularMethod(); 
} 

public void PopularMethod() 
{ 
    //Get calling method name 
} 

は、呼び出す関数のリストを取得するためにリフレクションを使用することが可能ですそれの体の中の "PopularMethod"機能に? [Main、ButtonClick、Button2Click]

更新:C# reflection and finding all references 私が探していたものはありましたか? woot!ありがとうございました

+0

確かに - 静的解析ツールのVisual Studio内と他のサードパーティのツールもこれを行うことができます。しかし、フレームワークに組み込まれたものはありません。 –

+0

@D Stanley私は、これらのツールが実際のコードを解析し、そのように宣言/用途を見つけることができると思います。なぜこれをプログラマチックにやりたいのですか? – GantTheWanderer

+1

ソリューションはこの[1](http://stackoverflow.com/a/5490526/324260)に似ている必要があります。 –

答えて

0

System.Diagnosticsをご覧ください。参考になるかもしれないStackTraceクラスがあります。

StackTrace st = new StackTrace(true); 
for(int i =0; i< st.FrameCount; i++) 
{ 
    // Note that high up the call stack, there is only 
    // one stack frame. 
    StackFrame sf = st.GetFrame(i); 
    Console.WriteLine(); 
    Console.WriteLine("High up the call stack, Method: {0}", 
     sf.GetMethod()); 

    Console.WriteLine("High up the call stack, Line Number: {0}", 
     sf.GetFileLineNumber()); 
} 
+0

これを使用して、PopularFunctionを呼び出すすべての呼び出された関数を見つけることができます。これは呼び出されていないものへの参照を見つけることができないため、これがすべての参照のリストを提供できるかどうかは不明です。 – GantTheWanderer

2

あなたはランタイムサービスがあなたのために、この情報を取得できるように使用できる属性があります:

public void PopularMethod([System.Runtime.CompilerServices.CallerMemberName] string memberName = "") 
{ 

} 

よりここに読むには: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx

+1

返信いただきありがとうございましたが、それは私が探しているものではありません。そのためには、PopularMethodが呼び出されている必要があります。私はより多くの方法を呼び出すことなく、C#のリフレクションを使用してプログラムの呼び出し階層を得ることを検討しています。 – user2326106

+0

私は今理解しています。これを見てください:http://stackoverflow.com/questions/31861762/finding-all-references-to-a-method-with-roslyn – JuanR

関連する問題