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项目时用以上特性。

相关文章:

  • 2021-11-24
  • 2021-09-15
  • 2021-07-25
  • 2021-06-06
  • 2022-12-23
  • 2021-06-12
猜你喜欢
  • 2022-02-18
  • 2021-08-22
  • 2021-08-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
相关资源
相似解决方案