C# 5.0 新特性之 CallerInformation
去年8月,Visual Studio 2012和.NET Framework 4.5已经完成了,在.NET Framework 4.5 的C# 5.0的新特性中,其中之一就是CallerInformation,今天跟大家谈谈。
CallerInformation的三个AttributeCallerInformation的三个Attribute可以用来获取方法调用者的信息,
这三个Attribute在 System.Runtime.CompilerServices 命名空间下,分别叫做CallerMemberNameAttribute,CallerFilePathAttribute和CallerLineNumberAttribute。
CallerMemberNameAttribute :用来获取方法调用者的名称
CallerFilePathAttribute :用来获取方法调用者的源代码文件路径
CallerLineNumberAttribute :用来获取方法调用者所在的行号
看了这三个Attribute的介绍,我们已经知道这是在调试程序时用的了,下面我们看一个小例子。
应用实例在Visual Studio 中新建一个Console Application,代码如下
using System; using System.Runtime.CompilerServices; namespace CallerInfomationExample { class Program { static void Main( string [] args) { TraceMessage( "Hello World." ); Console .WriteLine( "Pass any key to exit." ); Console .ReadKey(); } private static void TraceMessage( string message, [ CallerMemberName ] string callerMembername = "" , [ CallerFilePath ] string callerFilePath = "" , [ CallerLineNumber ] int callerLineNumber = 0) { Console .WriteLine(message); Console .WriteLine( "Caller member name is " + callerMembername); Console .WriteLine( "Caller file path is " + callerFilePath); Console .WriteLine( "Caller line number is " + callerLineNumber.ToString()); } } }
我们看到 TraceMessage 这个方法,在它的参数列表中,后面的三个参数加了刚才说的几个Attribute,在参数后面加默认值的是为了在方法调用时不用给它传这些参数。
当方法调用以后,嘿嘿,这些Attritbue起作用了,我们看看运行结果
再看看代码行号
注意,这里得到的行号是编译时的代码行号。
作者:朱恒成(Hamson)
出处: {Hamson} ( http://www.cnblogs.com/hamson/ )
版权声明:本文的版权归作者与博客园共同所有。转载时须在明显地方注明本文的详细链接,否则作者将追究其法律责任。
分类: .NET , C#
标签: C# , .NET4.5 , VS2012
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于C# 5.0 新特性之 CallerInformation的详细内容...