2016-12-13 8 views
7

dotnetコアアプリケーションで現在実行中のメソッドの名前を取得します。dotnetコアで現在実行中のメソッドの名前を取得します。

両方の方法のためのAPIはまだコアには存在しないように思われるが、通常のC#の例

でこれを行う方法の例の多くは(ありますhttps://github.com/dotnet/corefx/issues/1420を参照してください)

.netコアで実行メソッド名を取得できる別の方法はありますか?

+0

理由だけではなく、 'がNameOf(YourCurrentMethodを)'使用しない名前を付け? –

+0

また、より関連性の高いGitHubの問題はhttps://github.com/dotnet/corefx/issues/12496になります。 –

+0

'nameof(YourCurrentMethod)'は単に文字列を使用するよりもあまり良くありません。その方法は将来のリリースでも予定されています。多分答えはatm –

答えて

13

CallerMemberNameAttributeこのメソッドの呼び出し元のメソッドまたはプロパティ名を取得できます。

public void DoProcessing() 
{ 
    TraceMessage("Something happened."); 
} 

public void TraceMessage(string message, 
     [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", 
     [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", 
     [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) 
{ 
    System.Diagnostics.Trace.WriteLine("message: " + message); 
    System.Diagnostics.Trace.WriteLine("member name: " + memberName); 
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath); 
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber); 
} 

// Sample Output: 
// message: Something happened. 
// member name: DoProcessing 
// source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs 
// source line number: 31 
+0

thats awesome、thanks –

1

最も簡単な方法は、使用することです。

System.Reflection.MethodBase.GetCurrentMethod()

関連する問題