• C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用


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

  • 相关阅读:
    thinkphp笔记:错误页面定制
    HDU 1263
    HDU 1106
    HDU 1209
    HDU 5479
    HDU 2094
    git clone from Gighub Fail
    Github*
    Debian ABC --- 1st time ---5
    Debian ABC --- 1st time ---4
  • 原文地址:https://www.cnblogs.com/binsys/p/3015776.html
Copyright © 2020-2023  润新知