C# 5.0 新特性之 CallerInformation

去年8月,Visual Studio 2012和.NET Framework 4.5已经完成了,在.NET Framework 4.5 的C# 5.0的新特性中,其中之一就是CallerInformation,今天跟大家谈谈。

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起作用了,我们看看运行结果

image

再看看代码行号

image

注意,这里得到的行号是编译时的代码行号。

作者:朱恒成(Hamson) 
出处:{Hamson} (http://www.cnblogs.com/hamson/) 
版权声明:本文的版权归作者与博客园共同所有。转载时须在明显地方注明本文的详细链接,否则作者将追究其法律责任。
 
 
分类: .NETC#
标签: C#.NET4.5VS2012
原文地址:https://www.cnblogs.com/Leo_wl/p/2879186.html