好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C# 5.0 CallerMemberName CallerFilePath CallerLineN

C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用

C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用

C# 5.0 给我们带来了三个非常有用的编译器特性

CallerMemberName

CallerFilePath

CallerLineNumber

在C与C++中由下列字符帮助我们实现调试消息的文件行号

 01 . #define  debug_msg printf("%s[%d]:",__FILE__,__LINE__);printf

在.NET 4中与其功能相等的是

 new  StackTrace( true ).GetFrame( 1 ).GetMethod().Name

(注意,是功能相等,但实现不同,.NET4中是运行时获取,而C#5.0 中应该是编译时指定,原因参考以下)

在C#5.0中我们可以用以下代码实现调试信息文件行号获取:

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


用VS2012编译调试,便能看见文件,行号,调用者方法名称。

三个特性是.NET 4.5里面的,如果在.NET4中使用那么请定义一下特性:

 namespace   System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple  =  false , Inherited =  false  )]
      public   class   CallerMemberNameAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple  =  false , Inherited =  false  )]
      public   class   CallerFilePathAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple  =  false , Inherited =  false  )]
      public   class   CallerLineNumberAttribute : Attribute { }
} 

为了编译时.NET4和.NET4.5兼容,可以用 预处理 指令增加编译条件,在4.5下编译以上代码。

关键点来了,在.NET4下定义以上属性后,用VS2010编译,无相关信息输出,

用VS2012重新编译,则会输出相关信息(注意实在.NET4下),说明这个特性是编译器特性。也就是说我们可以在VS2012里写.NET4项目时用以上特性。

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于C# 5.0 CallerMemberName CallerFilePath CallerLineN的详细内容...

  阅读:57次