Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2336455
  • 博文数量: 527
  • 博客积分: 10343
  • 博客等级: 上将
  • 技术积分: 5565
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-26 23:05
文章分类

全部博文(527)

文章存档

2014年(4)

2012年(13)

2011年(19)

2010年(91)

2009年(136)

2008年(142)

2007年(80)

2006年(29)

2005年(13)

我的朋友

分类: WINDOWS

2007-12-10 13:02:57

C# 没有这样的宏!

下面的方法仅限于 Debug版. 从这个意义上说, 没有C中__FILE__, __LINE__的替代物.

但是, 与C语言相比, 下面的方法可以更得到更丰富的信息:

///



  /// Albeit the name contains dbg, it can also be used in release version,

  /// although there'll be no source files info

  ///


  /// Whether to output source lines, can output source lines

  /// only when the code is compiled with /debug+ option

  /// if output_src is true, control the context lines to output

  /// for source lines, equivalent to grep's -C option. If less than 0, reset to 0, which

  /// means only output the target line itself

  public static string get_dbg_info(bool output_src, int context_lines)
  {
      if( output_src && context_lines < 0)
        context_lines = 0;

      StackFrame sf = new StackFrame(1, true);
      MethodInfo mi = sf.GetMethod() as MethodInfo;
      StringBuilder sb = new StringBuilder();
      string fname = null;
      int which_line = -1;
      sb.Append( string.Format("[" + Environment.NewLine +
            "File /Line : {0}:{1}" + Environment.NewLine +
            "Class/Method: {2}.{3}" + Environment.NewLine,
            fname = sf.GetFileName(), which_line = sf.GetFileLineNumber(),
            mi.DeclaringType.FullName, mi.Name ) );

      if( output_src )
      {
        if(fname != null && File.Exists( fname ) )
        {
          int line_no = 1;
          using(StreamReader sr = File.OpenText( fname ) )
          {
            string line = null;
            while( (line = sr.ReadLine() ) != null )
            {
              if( (line_no < which_line) && line_no + context_lines >= which_line ||
                  (line_no >= which_line) && line_no - context_lines <= which_line )
              {
                sb.Append( string.Format("{0,4}:{1}{2}" + Environment.NewLine,
                      line_no,
                      (which_line == line_no)?"*":"" , line) );
              }
              line_no++;
              if( line_no > line_no + context_lines )
                break;
            }
          }
        }
        else
        {
          sb.Append("No source file available!" + Environment.NewLine );
        }
      }
      sb.Append( "]" );
      return sb.ToString();
  }


虽然名字中有个 dbg, 但是在release下也可以得到 类名, 函数名(在C99里可以通过 __func__ 宏得到当前函数名), 但在debug下的确可以得到更丰富的调试信息, 比如源代码, 文件名, 行号.

输出类似这样:
[
File /Line  : d:\work\CSharp\__file__.cs:25
Class/Method: Client.Main
  23:    try
  24:    {
  25:*      Console.WriteLine( get_dbg_info(true, 2) );
  26:    }
  27:    catch(Exception e)
]
阅读(1139) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~