StackTrace StackTrace StackTrace StackTrace Class

Definizione

Rappresenta un'analisi dello stack, vale a dire una raccolta ordinata di uno o più stack frame.Represents a stack trace, which is an ordered collection of one or more stack frames.

public ref class StackTrace
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class StackTrace
type StackTrace = class
Public Class StackTrace
Ereditarietà
StackTraceStackTraceStackTraceStackTrace
Attributi

Esempi

Nell'applicazione console riportata di seguito viene illustrato come creare StackTrace una semplice e scorrere i relativi frame per ottenere informazioni di debug e diagnostica.The following console application demonstrates how to create a simple StackTrace and iterate through its frames to obtain debugging and diagnostic information.

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
ref class StackTraceSample
{
private:
   ref class MyInternalClass
   {
   public:
      void ThrowsException()
      {
         try
         {
            throw gcnew Exception( "A problem was encountered." );
         }
         catch ( Exception^ e ) 
         {
            
            // Create a StackTrace that captures
            // filename, line number, and column
            // information for the current thread.
            StackTrace^ st = gcnew StackTrace( true );
            String^ stackIndent = "";
            for ( int i = 0; i < st->FrameCount; i++ )
            {
               
               // Note that at this level, there are five
               // stack frames, one for each method invocation.
               StackFrame^ sf = st->GetFrame( i );
               Console::WriteLine();
               Console::WriteLine( "{0}Method: {1}", stackIndent, sf->GetMethod() );
               Console::WriteLine( "{0}File: {1}", stackIndent, sf->GetFileName() );
               Console::WriteLine( "{0}Line Number: {1}", stackIndent, sf->GetFileLineNumber().ToString() );
               stackIndent = String::Concat( stackIndent, "  " );

            }
            throw e;
         }

      }

   };


protected:
   void MyProtectedMethod()
   {
      MyInternalClass^ mic = gcnew MyInternalClass;
      mic->ThrowsException();
   }


public:
   void MyPublicMethod()
   {
      MyProtectedMethod();
   }

};

int main()
{
   StackTraceSample^ sample = gcnew StackTraceSample;
   try
   {
      sample->MyPublicMethod();
   }
   catch ( Exception^ ) 
   {
      
      // Create a StackTrace that captures
      // filename, line number, and column
      // information for the current thread.
      StackTrace^ st = gcnew StackTrace( true );
      for ( int i = 0; i < st->FrameCount; i++ )
      {
         
         // For an executable built from C++, there
         // are two stack frames here: one for main,
         // and one for the _mainCRTStartup stub. 
         StackFrame^ sf = st->GetFrame( i );
         Console::WriteLine();
         Console::WriteLine( "High up the call stack, Method: {0}", sf->GetMethod()->ToString() );
         Console::WriteLine( "High up the call stack, Line Number: {0}", sf->GetFileLineNumber().ToString() );

      }
   }

}

/*
This console application produces the following output when
compiled with the Debug configuration.

  Method: Void ThrowsException()
  File: c:\samples\stacktraceframe\myclass.cpp
  Line Number: 20

    Method: Void MyProtectedMethod()
    File: c:\samples\stacktraceframe\myclass.cpp
    Line Number: 45

      Method: Void MyPublicMethod()
      File: c:\samples\stacktraceframe\myclass.cpp
      Line Number: 50
 
        Method: Int32 main()
        File: c:\samples\stacktraceframe\myclass.cpp
        Line Number: 56

          Method: UInt32 _mainCRTStartup()
          File:
          Line Number: 0

  High up the call stack, Method: Int32 main()
  High up the call stack, Line Number: 62

  High up the call stack, Method: UInt32 _mainCRTStartup()
  High up the call stack, Line Number: 0

This console application produces the following output when
compiled with the Release configuration.

  Method: Void ThrowsException()
  File:
  Line Number: 0

    Method: Int32 main()
    File:
    Line Number: 0

      Method: UInt32 _mainCRTStartup()
      File:
      Line Number: 0

  High up the call stack, Method: Int32 main()
  High up the call stack, Line Number: 0

  High up the call stack, Method: UInt32 _mainCRTStartup()
  High up the call stack, Line Number: 0

*/
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
'

Commenti

StackTracele informazioni saranno più informative con le configurazioni della build di debug.StackTrace information will be most informative with Debug build configurations. Per impostazione predefinita, le compilazioni di debug includono i simboli di debug, mentre le compilazioni di versioneBy default, Debug builds include debug symbols, while Release builds do not. I simboli di debug contengono la maggior parte delle informazioni sul file, il nome del metodo, il numero di riga StackFrame e StackTrace la colonna utilizzati per la costruzione di oggetti e.The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects.

StackTracepotrebbe non segnalare il numero di chiamate al metodo previste, a causa delle trasformazioni del codice che si verificano durante l'ottimizzazione.StackTrace might not report as many method calls as expected, due to code transformations that occur during optimization.

Costruttori

StackTrace() StackTrace() StackTrace() StackTrace()

Inizializza una nuova istanza della classe StackTrace dal frame del chiamante.Initializes a new instance of the StackTrace class from the caller's frame.

StackTrace(Boolean) StackTrace(Boolean) StackTrace(Boolean) StackTrace(Boolean)

Inizializza una nuova istanza della classe StackTrace dal frame del chiamante, acquisendo facoltativamente informazioni sull'origine.Initializes a new instance of the StackTrace class from the caller's frame, optionally capturing source information.

StackTrace(Exception) StackTrace(Exception) StackTrace(Exception) StackTrace(Exception)

Inizializza una nuova istanza della classe StackTrace utilizzando l'oggetto eccezione fornito.Initializes a new instance of the StackTrace class using the provided exception object.

StackTrace(Exception, Boolean) StackTrace(Exception, Boolean) StackTrace(Exception, Boolean) StackTrace(Exception, Boolean)

Inizializza una nuova istanza della classe StackTrace, utilizzando l'oggetto eccezione fornito e facoltativamente acquisendo informazioni sull'origine.Initializes a new instance of the StackTrace class, using the provided exception object and optionally capturing source information.

StackTrace(Exception, Int32) StackTrace(Exception, Int32) StackTrace(Exception, Int32) StackTrace(Exception, Int32)

Inizializza una nuova istanza della classe StackTrace utilizzando l'oggetto eccezione fornito e ignorando il numero di frame specificato.Initializes a new instance of the StackTrace class using the provided exception object and skipping the specified number of frames.

StackTrace(Exception, Int32, Boolean) StackTrace(Exception, Int32, Boolean) StackTrace(Exception, Int32, Boolean) StackTrace(Exception, Int32, Boolean)

Inizializza una nuova istanza della classe StackTrace utilizzando l'oggetto eccezione fornito, ignorando il numero di frame specificato ed eventualmente acquisendo le informazioni sull'origine.Initializes a new instance of the StackTrace class using the provided exception object, skipping the specified number of frames and optionally capturing source information.

StackTrace(Int32) StackTrace(Int32) StackTrace(Int32) StackTrace(Int32)

Inizializza una nuova istanza della classe StackTrace dal frame del chiamante, ignorando il numero di frame specificato.Initializes a new instance of the StackTrace class from the caller's frame, skipping the specified number of frames.

StackTrace(Int32, Boolean) StackTrace(Int32, Boolean) StackTrace(Int32, Boolean) StackTrace(Int32, Boolean)

Inizializza una nuova istanza della classe StackTrace dal frame del chiamante, ignorando il numero di frame specificato ed eventualmente acquisendo le informazioni sull'origine.Initializes a new instance of the StackTrace class from the caller's frame, skipping the specified number of frames and optionally capturing source information.

StackTrace(StackFrame) StackTrace(StackFrame) StackTrace(StackFrame) StackTrace(StackFrame)

Consente di inizializzare una nuova istanza della classe StackTrace che contiene un solo frame.Initializes a new instance of the StackTrace class that contains a single frame.

StackTrace(Thread, Boolean) StackTrace(Thread, Boolean) StackTrace(Thread, Boolean) StackTrace(Thread, Boolean)

Inizializza una nuova istanza della classe StackTrace per un thread specifico, acquisendo facoltativamente informazioni sull'origine.Initializes a new instance of the StackTrace class for a specific thread, optionally capturing source information.

Non utilizzare questo overload del costruttore.Do not use this constructor overload.

Campi

METHODS_TO_SKIP METHODS_TO_SKIP METHODS_TO_SKIP METHODS_TO_SKIP

Definisce l'impostazione predefinita per il numero di metodi da omettere dall'analisi dello stack.Defines the default for the number of methods to omit from the stack trace. Questo campo è costante.This field is constant.

Proprietà

FrameCount FrameCount FrameCount FrameCount

Ottiene il numero di frame nell'analisi dello stack.Gets the number of frames in the stack trace.

Metodi

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetFrame(Int32) GetFrame(Int32) GetFrame(Int32) GetFrame(Int32)

Ottiene lo stack frame specificato.Gets the specified stack frame.

GetFrames() GetFrames() GetFrames() GetFrames()

Restituisce una copia di tutti gli stack frame nella traccia corrente dello stack.Returns a copy of all stack frames in the current stack trace.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Funge da funzione hash predefinita.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Compila una rappresentazione leggibile dell'analisi dello stack.Builds a readable representation of the stack trace.

Sicurezza

InheritanceDemand
per consentire agli eredi di accedere al codice non gestito.for the ability of inheritors to access unmanaged code. Enumerazione associata: UnmanagedCode.Associated enumeration: UnmanagedCode. Questa classe non può essere ereditata da codice parzialmente attendibile.This class cannot be inherited by partially trusted code.

Si applica a

Vedi anche