西秀岭

导航

C# 中使用特性获得函数被调用的路径,行号和函数


 自从 .net framework 4.5  增加了几个特性来获得函数的调用路径(CallerFilePath),调用行号(CallerLineNumber),和调用函数(CallerMemberName)

 

using System;
using System.Runtime.CompilerServices;

namespace myattribute
{
  class Program
    {
        static void Print(string str,
            [CallerFilePath] string filePath = "",
            [CallerLineNumber] int num = 0,
            [CallerMemberName] string name = "")
        {
            Console.WriteLine(str);
            Console.WriteLine("filePath {0}", filePath);
            Console.WriteLine("Line {0}", num);
            Console.WriteLine("Call from {0}", name);
        }

        static void Main(string[] args)
        {
            Print("nothing");
            Console.ReadKey();
        }
    }
}

运行结果如下:

 

有了这个功能,我们在日志输出时就方便了很多,可以提供跟多的信息了,方便问题调查。  

posted on 2019-02-27 11:48  西秀岭  阅读(1081)  评论(0编辑  收藏  举报