LocalVariableInfo 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.
Descobre os atributos de uma variável local e fornece acesso aos metadados de variável local.
public ref class LocalVariableInfo
public class LocalVariableInfo
[System.Runtime.InteropServices.ComVisible(true)]
public class LocalVariableInfo
type LocalVariableInfo = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type LocalVariableInfo = class
Public Class LocalVariableInfo
- Herança
-
LocalVariableInfo
- Derivado
- Atributos
Exemplos
O exemplo a seguir define um método de teste chamado MethodBodyExample
e exibe suas informações de variável local. O GetMethodBody método é usado para obter um MethodBody objeto para o método de teste. Em LocalVariables seguida, a propriedade é usada para obter uma lista de LocalVariableInfo objetos e para exibir seus tipos e ordem de índice.
Este exemplo de código faz parte de um exemplo maior fornecido para a MethodBody classe .
#using <System.dll>
using namespace System;
using namespace System::Reflection;
public ref class Example
{
// The Main method contains code to analyze this method, using
// the properties and methods of the MethodBody class.
public:
void MethodBodyExample(Object^ arg)
{
// Define some local variables. In addition to these variables,
// the local variable list includes the variables scoped to
// the catch clauses.
int var1 = 42;
String^ var2 = "Forty-two";
try
{
// Depending on the input value, throw an ArgumentException or
// an ArgumentNullException to test the Catch clauses.
if (arg == nullptr)
{
throw gcnew ArgumentNullException("The argument cannot " +
"be null.");
}
if (arg->GetType() == String::typeid)
{
throw gcnew ArgumentException("The argument cannot " +
"be a string.");
}
}
// There is no Filter clause in this code example. See the Visual
// Basic code for an example of a Filter clause.
// This catch clause handles the ArgumentException class, and
// any other class derived from Exception.
catch (ArgumentException^ ex)
{
Console::WriteLine("Ordinary exception-handling clause caught:" +
" {0}", ex->GetType());
}
finally
{
var1 = 3033;
var2 = "Another string.";
}
}
};
int main()
{
// Get method body information.
MethodInfo^ mi =
Example::typeid->GetMethod("MethodBodyExample");
MethodBody^ mb = mi->GetMethodBody();
Console::WriteLine("\r\nMethod: {0}", mi);
// Display the general information included in the
// MethodBody object.
Console::WriteLine(" Local variables are initialized: {0}",
mb->InitLocals);
Console::WriteLine(" Maximum number of items on the operand " +
"stack: {0}", mb->MaxStackSize);
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
// Get method body information.
MethodInfo mi = typeof(Example).GetMethod("MethodBodyExample");
MethodBody mb = mi.GetMethodBody();
Console.WriteLine("\r\nMethod: {0}", mi);
// Display the general information included in the
// MethodBody object.
Console.WriteLine(" Local variables are initialized: {0}",
mb.InitLocals);
Console.WriteLine(" Maximum number of items on the operand stack: {0}",
mb.MaxStackSize);
Imports System.Reflection
Public Class Example
Public Shared Sub Main()
' Demonstrate the effect of the Visual Basic When keyword, which
' generates a Filter clause in the Try block.
Dim e As New Example()
Console.WriteLine()
e.MethodBodyExample("String argument")
e.MethodBodyExample(Nothing)
' Get method body information.
Dim mi As MethodInfo = _
GetType(Example).GetMethod("MethodBodyExample")
Dim mb As MethodBody = mi.GetMethodBody()
Console.WriteLine(vbCrLf & "Method: {0}", mi)
' Display the general information included in the
' MethodBody object.
Console.WriteLine(" Local variables are initialized: {0}", _
mb.InitLocals)
Console.WriteLine(" Maximum number of items on the operand stack: {0}", _
mb.MaxStackSize)
// Display information about the local variables in the
// method body.
Console::WriteLine();
for each (LocalVariableInfo^ lvi in mb->LocalVariables)
{
Console::WriteLine("Local variable: {0}", lvi);
}
// Display information about the local variables in the
// method body.
Console.WriteLine();
foreach (LocalVariableInfo lvi in mb.LocalVariables)
{
Console.WriteLine("Local variable: {0}", lvi);
}
' Display information about the local variables in the
' method body.
Console.WriteLine()
For Each lvi As LocalVariableInfo In mb.LocalVariables
Console.WriteLine("Local variable: {0}", lvi)
Next
// The Main method contains code to analyze this method, using
// the properties and methods of the MethodBody class.
public:
void MethodBodyExample(Object^ arg)
{
// Define some local variables. In addition to these variables,
// the local variable list includes the variables scoped to
// the catch clauses.
int var1 = 42;
String^ var2 = "Forty-two";
try
{
// Depending on the input value, throw an ArgumentException or
// an ArgumentNullException to test the Catch clauses.
if (arg == nullptr)
{
throw gcnew ArgumentNullException("The argument cannot " +
"be null.");
}
if (arg->GetType() == String::typeid)
{
throw gcnew ArgumentException("The argument cannot " +
"be a string.");
}
}
// There is no Filter clause in this code example. See the Visual
// Basic code for an example of a Filter clause.
// This catch clause handles the ArgumentException class, and
// any other class derived from Exception.
catch (ArgumentException^ ex)
{
Console::WriteLine("Ordinary exception-handling clause caught:" +
" {0}", ex->GetType());
}
finally
{
var1 = 3033;
var2 = "Another string.";
}
}
}
// The Main method contains code to analyze this method, using
// the properties and methods of the MethodBody class.
public void MethodBodyExample(object arg)
{
// Define some local variables. In addition to these variables,
// the local variable list includes the variables scoped to
// the catch clauses.
int var1 = 42;
string var2 = "Forty-two";
try
{
// Depending on the input value, throw an ArgumentException or
// an ArgumentNullException to test the Catch clauses.
if (arg == null)
{
throw new ArgumentNullException("The argument cannot be null.");
}
if (arg.GetType() == typeof(string))
{
throw new ArgumentException("The argument cannot be a string.");
}
}
// This filter clause selects only exceptions that derive
// from the ArgumentException class.
// Other exceptions, including ArgumentException itself,
// are not handled by this filter clause.
catch (ArgumentException ex) when (ex.GetType().IsSubclassOf(typeof(ArgumentException)))
{
Console.WriteLine("Filter clause caught: {0}", ex.GetType());
}
// This catch clause handles the ArgumentException class, and
// any other class derived from Exception.
catch(Exception ex)
{
Console.WriteLine("Ordinary exception-handling clause caught: {0}",
ex.GetType());
}
finally
{
var1 = 3033;
var2 = "Another string.";
}
}
}
// This code example produces output similar to the following:
//
//Method: Void MethodBodyExample(System.Object)
// Local variables are initialized: True
// Maximum number of items on the operand stack: 2
End Sub
' This test method is executed at the beginning of Main, to show
' how the Filter clause works. The Filter clause is generated by
' a Visual Basic When expression. If arg is Nothing, this method
' throws ArgumentNullException, which is caught by the filter
' clause. If arg is a string, the method throws ArgumentException,
' which does not match the filter clause.
'
' Sub Main also contains code to analyze this method, using
' the properties and methods of the MethodBody class.
Public Sub MethodBodyExample(ByVal arg As Object)
' Define some local variables. In addition to these variables,
' the local variable list includes the variables scoped to
' the catch clauses.
Dim var1 As Integer = 42
Dim var2 As String = "Forty-two"
Try
' Depending on the input value, throw an ArgumentException or
' an ArgumentNullException to test the Catch clauses.
'
If arg Is Nothing Then
Throw New ArgumentNullException("The argument cannot be Nothing.")
End If
If arg.GetType() Is GetType(String) Then
Throw New ArgumentException("The argument cannot be a string.")
End If
' The When expression makes this a filter clause. The expression
' selects only exceptions that derive from the ArgumentException
' class. Other exceptions, including ArgumentException itself,
' are not handled by this filter clause.
Catch ex As ArgumentException _
When ex.GetType().IsSubclassOf(GetType(ArgumentException))
Console.WriteLine("Filter clause caught: {0}", ex.GetType())
' This catch clause handles the ArgumentException class, and
' any other class derived from Exception.
Catch ex As Exception
Console.WriteLine("Ordinary exception-handling clause caught: {0}", _
ex.GetType())
Finally
var1 = 3033
var2 = "Another string."
End Try
End Sub
End Class
' This code example produces output similar to the following:
'
'Ordinary exception-handling clause caught: System.ArgumentException
'Filter clause caught: System.ArgumentNullException
'
'Method: Void MethodBodyExample(System.Object)
' Local variables are initialized: True
' Maximum number of items on the operand stack: 3
//Local variable: System.ArgumentException (0)
//Local variable: System.String (1)
//Local variable: System.Int32 (2)
//
//Local variable: System.Int32 (0)
//Local variable: System.String (1)
//Local variable: System.Exception (2)
//Local variable: System.Boolean (3)
'
'Local variable: System.Int32 (0)
'Local variable: System.String (1)
'Local variable: System.ArgumentException (2)
'Local variable: System.Exception (3)
Comentários
Para obter uma lista de variáveis locais em um método, use a MethodBody.LocalVariables propriedade . Use o MethodBase.GetMethodBody método para obter o MethodBody para um MethodInfo objeto .
Observação
Nomes de variáveis locais não são persistidos em metadados. Na MSIL (linguagem intermediária da Microsoft), as variáveis locais são acessadas por sua posição na assinatura de variável local.
Construtores
LocalVariableInfo() |
Inicializa uma nova instância da classe LocalVariableInfo. |
Propriedades
IsPinned |
Obtém um valor Boolean que indica se o objeto referenciado pela variável local está fixado na memória. |
LocalIndex |
Obtém o índice da variável local dentro do corpo de método. |
LocalType |
Obtém o tipo da variável local. |
Métodos
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
GetHashCode() |
Serve como a função de hash padrão. (Herdado de Object) |
GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual. (Herdado de Object) |
ToString() |
Retorna uma cadeia de caracteres legível pelo usuário que descreve a variável local. |