某些场景需要获取当前执行的实时信息(行号,文件名,方法名),c# 在 .NET Frameworks 4.5 中 System.Runtime.CompilerServices 命名空间下新增了3个attribute:CallerLineNumber, CallerFilePath, CallerMemberName 来简化这些信息的获取。
以下是个示例的log方法:
public void Log([CallerLineNumber] int line = -1,
[CallerFilePath] string path = null,
[CallerMemberName] string name = null)
{
WriteLine((line < 0) ?”No line” :”Line” + line);
WriteLine((path ==> null) ?”No file path” : path);
WriteLine((name == null) ?”No member name” : name);
WriteLine();
}
对于CallerMemberName来说,他对于INotifyPropertyChanged 接口实现有巨大的帮助,微软官方也在msdn上推荐使用 这种方法