zoukankan      html  css  js  c++  java
  • C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用

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

  • 相关阅读:
    Android NumberPicker和DatePicker分割线颜色设置
    用来解析,格式化,存储和验证国际电话号码:libphonenumber
    Unbutu网卡驱动安装(Intel内置网卡8086:15b8)
    Android版本判断
    Ubuntu中、英文环境设置
    adb常用命令介绍
    Android Environment 类详解
    Android字符串相关类
    Android字符串相关类
    Android字符串相关类
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3016025.html
Copyright © 2011-2022 走看看