当抛出异常时,我尝试获取文件名和源代码行号。 但我什么也没得到。
class Program
{
static void Main(string[] args)
{
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException exception)
{
var stackTrace = new StackTrace(exception);
var currentFrame = stackTrace.GetFrame(0);
var fileName = currentFrame.GetFileName();
var sourceLineNumber = currentFrame.GetFileLineNumber();
Console.WriteLine("File Name: " + fileName);
Console.WriteLine("Source line number: " + sourceLineNumber);
Console.ReadKey();
}
}
}
只有一帧可用。所以我在 GetFrame(index)
中使用索引 0。
最佳答案
我会编写一个方法并使用 CallerFilePath
、CallerLineNumber
和 CallerMemberName
属性
public void Log([CallerFilePath]string path="",[CallerLineNumber]int lineNumber=0,[CallerMemberName] string memberName="")
{
Console.WriteLine(path + " " + lineNumber + " " + memberName);
}
用法:Log()
了解更多信息:https://msdn.microsoft.com/en-us/library/hh534540.aspx
关于c# - 抛出异常时从堆栈跟踪和帧中获取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31518803/