通常你的需求,我會採用NLog或log4net來做...
但假設你真的想自己寫程式做這種dirty work,
那麼你需要使用System.Diagnostics.StackTrace類別。
下面是個簡單範例,你在配合寫在你的Utililty Class內的一個Method:
// typeof 要改為你的Utility Class
Type targetType = typeof( YourClass );
string methodName = string.Empty;
string className = string.Empty;
string fileName = string.Empty;
string lineNumber = string.Empty;
int frameIndex = 0;
// 利用StackTrace,透過StackFrame來查找程式位置。
// StackTrace有很多個Constructor,請自行依你需求修改。
StackTrace stackTrace = new StackTrace( true );
while( frameIndex < stackTrace.FrameCount )
{
StackFrame frame = stackTrace.GetFrame( frameIndex );
if( frame != null && frame.GetMethod().DeclaringType == targetType )
{
break;
}
frameIndex++;
}
while( frameIndex < stackTrace.FrameCount )
{
StackFrame frame = stackTrace.GetFrame( frameIndex );
if( frame != null && frame.GetMethod().DeclaringType != targetType )
{
break;
}
frameIndex++;
}
if( frameIndex < stackTrace.FrameCount )
{
StackFrame locationFrame = stackTrace.GetFrame( frameIndex );
if( locationFrame != null )
{
System.Reflection.MethodBase method = locationFrame.GetMethod();
if( method != null )
{
methodName = method.Name;
if( method.DeclaringType != null )
{
className = method.DeclaringType.FullName;
}
}
fileName = locationFrame.GetFileName();
lineNumber = locationFrame.GetFileLineNumber().ToString();
}
}
至此,className、fileName、lineNumber應該已經是調用這個method的來源位置了。
※ 引述《scdog (just do it)》之銘言:
: 小弟想debug
: 印出目前某行程式碼所在行數
: 該如何做
: thx
--
對於已經無法擁有的
唯一能做的是
不要忘記
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.125.251.180