C# 5.0 新特性之 CallerInformation
2013-01-27 22:56
253 查看
去年8月,Visual Studio 2012和.NET Framework 4.5已经完成了,在.NET Framework 4.5 的C# 5.0的新特性中,其中之一就是CallerInformation,今天跟大家谈谈。
这三个Attribute在System.Runtime.CompilerServices命名空间下,分别叫做CallerMemberNameAttribute,CallerFilePathAttribute和CallerLineNumberAttribute。
CallerMemberNameAttribute:用来获取方法调用者的名称
CallerFilePathAttribute:用来获取方法调用者的源代码文件路径
CallerLineNumberAttribute:用来获取方法调用者所在的行号
看了这三个Attribute的介绍,我们已经知道这是在调试程序时用的了,下面我们看一个小例子。
我们看到TraceMessage这个方法,在它的参数列表中,后面的三个参数加了刚才说的几个Attribute,在参数后面加默认值的是为了在方法调用时不用给它传这些参数。
当方法调用以后,嘿嘿,这些Attritbue起作用了,我们看看运行结果
再看看代码行号
注意,这里得到的行号是编译时的代码行号。
作者:朱恒成(Hamson)
出处:{Hamson} (http://www.cnblogs.com/hamson/)
版权声明:本文的版权归作者与博客园共同所有。转载时须在明显地方注明本文的详细链接,否则作者将追究其法律责任。
CallerInformation的三个Attribute
CallerInformation的三个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/)
版权声明:本文的版权归作者与博客园共同所有。转载时须在明显地方注明本文的详细链接,否则作者将追究其法律责任。
相关文章推荐
- C# 5.0中新增特性
- 转:[你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- C# 5.0 新特性——Async和Await
- [转][你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- C#5.0特性之 async异步方法
- C# 5.0将带来的五大新特性
- C# 5.0中新增特性
- C#5.0的新特性之全新的异步编程模型
- [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- C# 5.0新特性:Async和Await使异步编程更简单
- Atitit. c# 语法新特性 c#2.0 3.0 4.0 4.5 5.0 6.0 attilax总结 1. 版本历史 1 1.1. C# 1.0-纯粹的面向对象 2 1.2. C# 2.0
- C# 5.0中新增特性
- Hello C#5.0新特性
- C# 5.0 新特性——Async和Await使异步编程更简单
- C# 5.0将带来的五大新特性
- [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- 关于C#5.0异步编程与6.0新特性的总结
- [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
- [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单