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項目時用以上特性。
轉載于:https://www.cnblogs.com/binsys/archive/2013/04/11/3015776.html
總結
以上是生活随笔為你收集整理的C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【will】JS去字符串首尾空格
- 下一篇: C语言scanf函数奇遇记