デバッグ情報 プリプロセッサの代わり
FAQっぽい話になりますが。
.NETでも__FILE__や__LINE__みたいなものを使いたいという人達が居ますね(´ω`)
やる気があるならSystem.Diagnostics.StackTraceから情報も取れるわけで。
例えばlog4netなんかのコードから抜粋してみると、こんなカンジになっていますが。
StackTrace stack = new StackTrace( true ); int frameIndex = 0; while( frameIndex < stack.FrameCount ) { StackFrame frame = stack.GetFrame( frameIndex ); if ( ( frame != null ) && ( frame.GetMethod().DeclaringType == boundaryType ) ) { break; } frameIndex++; } while( frameIndex < stack.FrameCount ) { StackFrame frame = stack.GetFrame( frameIndex ); if ( ( frame != null ) && ( frame.GetMethod().DeclaringType != boundaryType ) ) { break; } frameIndex++; } if ( frameIndex < stack.FrameCount ) { StackFrame location = stack.GetFrame(frameIndex); if ( location != null ) { MethodBase method = location.GetMethod(); if (method != null) { メソッド名 = method.Name; if ( method.DeclaringType != null ) { クラス名 = method.DeclaringType.FullName; } } ファイル名 = location.GetFileName(); 行番号 = location.GetFileLineNumber(); } }
ファイル名と行番号はデバッグビルドでないと取れませんけどね(・∀・)
正常系で使うとコストの高い処理だし、異常系だったらExceptionのStackTraceで良いと思うので、個人的にはこの処理をあまり使おうとは思いませんけどね(´ω`)
まあ、どうしてもというなら。