欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用介紹方法

 更新時間:2013年04月12日 11:26:24   作者:  
本篇文章,小編為大家介紹關(guān)于C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用介紹方法,有需要的朋友可以參考一下

C# 5.0 給我們帶來了三個非常有用的編譯器特性

CallerMemberName

CallerFilePath

CallerLineNumber

在C與C++中由下列字符幫助我們實現(xiàn)調(diào)試消息的文件行號

復(fù)制代碼 代碼如下:

.#define debug_msg printf("%s[%d]:",__FILE__,__LINE__);printf

在.NET 4中與其功能相等的是

復(fù)制代碼 代碼如下:

new StackTrace(true).GetFrame(1).GetMethod().Name(注意,是功能相等,但實現(xiàn)不同,.NET4中是運行時獲取,而C#5.0 中應(yīng)該是編譯時指定,原因參考以下)

在C#5.0中我們可以用以下代碼實現(xiàn)調(diào)試信息文件行號獲取:

復(fù)制代碼 代碼如下:

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編譯調(diào)試,便能看見文件,行號,調(diào)用者方法名稱。

三個特性是.NET 4.5里面的,如果在.NET4中使用那么請定義一下特性:

復(fù)制代碼 代碼如下:

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兼容,可以用預(yù)處理指令增加編譯條件,在4.5下編譯以上代碼。
關(guān)鍵點來了,在.NET4下定義以上屬性后,用VS2010編譯,無相關(guān)信息輸出,
用VS2012重新編譯,則會輸出相關(guān)信息(注意實在.NET4下),說明這個特性是編譯器特性。也就是說我們可以在VS2012里寫.NET4項目時用以上特性。

相關(guān)文章

最新評論