StackTrace Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Representa um rastreamento da pilha, que é uma coleção ordenada de um ou mais quadros da pilha.
public ref class StackTrace sealed
public ref class StackTrace
public sealed class StackTrace
[System.Serializable]
public class StackTrace
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
public class StackTrace
type StackTrace = class
[<System.Serializable>]
type StackTrace = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type StackTrace = class
Public NotInheritable Class StackTrace
Public Class StackTrace
- Herança
-
StackTrace
- Atributos
Exemplos
O aplicativo de console a seguir demonstra como criar um simples StackTrace e iterar por meio de seus quadros para obter informações de depuração e diagnóstico.
using System;
using System.Diagnostics;
class StackTraceSample
{
[STAThread]
static void Main(string[] args)
{
StackTraceSample sample = new StackTraceSample();
try
{
sample.MyPublicMethod();
}
catch (Exception)
{
// Create a StackTrace that captures
// filename, line number, and column
// information for the current thread.
StackTrace st = new StackTrace(true);
for(int i =0; i< st.FrameCount; i++ )
{
// Note that high up the call stack, there is only
// one stack frame.
StackFrame sf = st.GetFrame(i);
Console.WriteLine();
Console.WriteLine("High up the call stack, Method: {0}",
sf.GetMethod());
Console.WriteLine("High up the call stack, Line Number: {0}",
sf.GetFileLineNumber());
}
}
}
public void MyPublicMethod ()
{
MyProtectedMethod();
}
protected void MyProtectedMethod ()
{
MyInternalClass mic = new MyInternalClass();
mic.ThrowsException();
}
class MyInternalClass
{
public void ThrowsException()
{
try
{
throw new Exception("A problem was encountered.");
}
catch (Exception e)
{
// Create a StackTrace that captures filename,
// line number and column information.
StackTrace st = new StackTrace(true);
string stackIndent = "";
for(int i =0; i< st.FrameCount; i++ )
{
// Note that at this level, there are four
// stack frames, one for each method invocation.
StackFrame sf = st.GetFrame(i);
Console.WriteLine();
Console.WriteLine(stackIndent + " Method: {0}",
sf.GetMethod() );
Console.WriteLine( stackIndent + " File: {0}",
sf.GetFileName());
Console.WriteLine( stackIndent + " Line Number: {0}",
sf.GetFileLineNumber());
stackIndent += " ";
}
throw e;
}
}
}
}
/*
This console application produces the following output when
compiled with the Debug configuration.
Method: Void ThrowsException()
File: c:\samples\stacktraceframe\myclass.cs
Line Number: 59
Method: Void MyProtectedMethod()
File: c:\samples\stacktraceframe\myclass.cs
Line Number: 45
Method: Void MyPublicMethod()
File: c:\samples\stacktraceframe\myclass.cs
Line Number: 39
Method: Void Main(System.String[])
File: c:\samples\stacktraceframe\myclass.cs
Line Number: 13
High up the call stack, Method: Void Main(System.String[])
High up the call stack, Line Number: 20
This console application produces the following output when
compiled with the Release configuration.
Method: Void ThrowsException()
File:
Line Number: 0
Method: Void Main(System.String[])
File:
Line Number: 0
High up the call stack, Method: Void Main(System.String[])
High up the call stack, Line Number: 0
*/
Imports System.Diagnostics
Class StackTraceSample
<STAThread()> _
Public Shared Sub Main()
Dim sample As New StackTraceSample()
Try
sample.MyPublicMethod()
Catch
' Create a StackTrace that captures
' filename, line number, and column
' information for the current thread.
Dim st As New StackTrace(True)
Dim i As Integer
For i = 0 To st.FrameCount - 1
' Note that high up the call stack, there is only
' one stack frame.
Dim sf As StackFrame = st.GetFrame(i)
Console.WriteLine()
Console.WriteLine("High up the call stack, Method: {0}", _
sf.GetMethod())
Console.WriteLine("High up the call stack, Line Number: {0}", _
sf.GetFileLineNumber())
Next i
End Try
End Sub
Public Sub MyPublicMethod()
MyProtectedMethod()
End Sub
Protected Sub MyProtectedMethod()
Dim mic As New MyInternalClass()
mic.ThrowsException()
End Sub
Class MyInternalClass
Public Sub ThrowsException()
Try
Throw New Exception("A problem was encountered.")
Catch e As Exception
' Create a StackTrace that captures filename,
' line number and column information.
Dim st As New StackTrace(True)
Dim stackIndent As String = ""
Dim i As Integer
For i = 0 To st.FrameCount - 1
' Note that at this level, there are four
' stack frames, one for each method invocation.
Dim sf As StackFrame = st.GetFrame(i)
Console.WriteLine()
Console.WriteLine(stackIndent + " Method: {0}", _
sf.GetMethod())
Console.WriteLine(stackIndent + " File: {0}", _
sf.GetFileName())
Console.WriteLine(stackIndent + " Line Number: {0}", _
sf.GetFileLineNumber())
stackIndent += " "
Next i
Throw e
End Try
End Sub
End Class
End Class
' This console application produces the following output when
' compiled with the Debug configuration.
'
' Method: Void ThrowsException()
' File: c:\pp\samples\stacktraceframe\myclass.vb
' Line Number: 55
'
' Method: Void MyProtectedMethod()
' File: c:\pp\samples\stacktraceframe\myclass.vb
' Line Number: 42
'
' Method: Void MyPublicMethod()
' File: c:\pp\samples\stacktraceframe\myclass.vb
' Line Number: 37
'
' Method: Void Main(System.String[])
' File: c:\pp\samples\stacktraceframe\myclass.vb
' Line Number: 13
'
' High up the call stack, Method: Void Main(System.String[])
' High up the call stack, Line Number: 18
'
'
' This console application produces the following output when
' compiled with the Release configuration.
'
' Method: Void ThrowsException()
' File:
' Line Number: 0
'
' Method: Void Main(System.String[])
' File:
' Line Number: 0
'
' High up the call stack, Method: Void Main()
' High up the call stack, Line Number: 0
'
Comentários
StackTrace as informações serão mais esclarecedoras com as configurações de compilação de depuração. Por padrão, os builds de depuração incluem símbolos de depuração, enquanto os builds de versão não. Os símbolos de depuração contêm a maioria das informações de arquivo, nome do método, número de linha, e coluna usadas na construção dos objetos StackFrame e StackTrace.
StackTrace pode não registrar tantas chamadas de método quanto eram esperadas, devido a modificações de código que ocorrem durante a otimização.
Construtores
| Nome | Description |
|---|---|
| StackTrace() |
Inicializa uma nova instância da classe do StackTrace quadro do chamador. |
| StackTrace(Boolean) |
Inicializa uma nova instância da classe do StackTrace quadro do chamador, opcionalmente capturando informações de origem. |
| StackTrace(Exception, Boolean) |
Inicializa uma nova instância da StackTrace classe, usando o objeto de exceção fornecido e, opcionalmente, capturando informações de origem. |
| StackTrace(Exception, Int32, Boolean) |
Inicializa uma nova instância da StackTrace classe usando o objeto de exceção fornecido, ignorando o número especificado de quadros e, opcionalmente, capturando informações de origem. |
| StackTrace(Exception, Int32) |
Inicializa uma nova instância da StackTrace classe usando o objeto de exceção fornecido e ignorando o número especificado de quadros. |
| StackTrace(Exception) |
Inicializa uma nova instância da StackTrace classe usando o objeto de exceção fornecido. |
| StackTrace(Int32, Boolean) |
Inicializa uma nova instância da classe do StackTrace quadro do chamador, ignorando o número especificado de quadros e, opcionalmente, capturando informações de origem. |
| StackTrace(Int32) |
Inicializa uma nova instância da classe do StackTrace quadro do chamador, ignorando o número especificado de quadros. |
| StackTrace(StackFrame) |
Inicializa uma nova instância da StackTrace classe que contém um único quadro. |
| StackTrace(Thread, Boolean) |
Obsoleto.
Inicializa uma nova instância da StackTrace classe para um thread específico, opcionalmente capturando informações de origem. Não use essa sobrecarga de construtor. |
Campos
| Nome | Description |
|---|---|
| METHODS_TO_SKIP |
Define o padrão para o número de métodos a serem omitir do rastreamento de pilha. Esse campo é constante. |
Propriedades
| Nome | Description |
|---|---|
| FrameCount |
Obtém o número de quadros no rastreamento de pilha. |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetFrame(Int32) |
Obtém o quadro de pilha especificado. |
| GetFrames() |
Retorna uma cópia de todos os quadros de pilha no rastreamento de pilha atual. |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| ToString() |
Cria uma representação legível do rastreamento de pilha. |