C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用
2013-04-12 10:01
477 查看
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项目时用以上特性。
相关文章推荐
- C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用
- 关于C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用介绍方法
- C# 5.0 CallerMemberName CallerFilePath CallerLineNumber获取调用方法名称,路径,行号
- 在 .NET 4.0 中使用 .NET 4.5 中新增的特性(CallerMemberNameAttribute/CallerFilePathAttribute/CallerLineNumberAttribute)
- unable to install breakpoint in ...(file name) due to miss line number attributes.
- Python使用eval强制转换字符串为字典时报错:File "<string>", line 1, in <module> NameError: name 'nan' is not defined
- C# 中使用Image.FromFile(string path)后,提示该文件正在被另一进程使用XXX的问题
- C# 中使用Image.FromFile(string path)后,提示该文件正在被另一进程使用XXX的问题
- C#控制台基础 使用file.readallline读取中文的时候乱码
- how to get the caller's module name, file name , function name and line number?
- 字符流FileReader,FileWriter,BufferedWriter,BufferedReader,装饰设计模式,LineNumberReader
- C#(Winform)的SaveFileDialog(文件保存对话框)控件使用
- vba使用win32 API(GetOpenFileName )实现打开文件对话框
- (六)Net Core项目使用Controller之一 c# log4net 不输出日志 .NET Standard库引用导致的FileNotFoundException探究 获取json串里的某个属性值 common.js 如何调用common.js js 筛选数据 Join 具体用法
- mac OS 使用SVN命令行工具报 xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)
- C# 使用System.IO.File.Create
- CocosEditor-java加载图片出错cocos2d: fullPathForFilename: No file found at main.plist. Possible missing fi
- C#使用HTML文件中的file文件上传,用C#代码接收上传文件
- 如何使用PathFileExists
- 34.Linux-printk分析、使用__FILE__, __FUNCTION__, __LINE__ 调试