作者petrushka (不放过自己)
看板C_Sharp
标题Re: [问题] 如何印出目前所在程式码行数
时间Thu May 20 16:33:11 2010
通常你的需求,我会采用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