MethodBase.Invoke Método

Definição

Invoca o método ou construtor refletido por esta instância MethodInfo.Invokes the method or constructor reflected by this MethodInfo instance.

Sobrecargas

Invoke(Object, Object[])

Invoca o método ou o construtor representado pela instância atual, usando os parâmetros especificados.Invokes the method or constructor represented by the current instance, using the specified parameters.

Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Quando substituído em uma classe derivada, invoca o método ou o construtor refletido com parâmetros especificados.When overridden in a derived class, invokes the reflected method or constructor with the given parameters.

Invoke(Object, Object[])

Invoca o método ou o construtor representado pela instância atual, usando os parâmetros especificados.Invokes the method or constructor represented by the current instance, using the specified parameters.

public:
 System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public object Invoke (object obj, object[] parameters);
member this.Invoke : obj * obj[] -> obj
Public Function Invoke (obj As Object, parameters As Object()) As Object

Parâmetros

obj
Object

O objeto no qual o método ou o construtor será invocado.The object on which to invoke the method or constructor. Se um método for estático, esse argumento será ignorado.If a method is static, this argument is ignored. Se um construtor for estático, esse argumento deverá ser null ou uma instância da classe que define o construtor.If a constructor is static, this argument must be null or an instance of the class that defines the constructor.

parameters
Object[]

Uma lista de argumentos para o construtor ou método invocado.An argument list for the invoked method or constructor. Esta é uma matriz de objetos com o mesmo número, ordem e tipo que os parâmetros do método ou do construtor a ser invocado.This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. Se não houver nenhum parâmetro, parameters deverá ser null.If there are no parameters, parameters should be null.

Se o método ou construtor representado por esta instância usar um parâmetro ref (ByRef no Visual Basic), nenhum atributo especial será necessário para esse parâmetro, a fim de invocar o método ou construtor com o uso dessa função.If the method or constructor represented by this instance takes a ref parameter (ByRef in Visual Basic), no special attribute is required for that parameter in order to invoke the method or constructor using this function. Qualquer objeto nesta matriz que não for inicializado explicitamente com um valor conterá o valor padrão desse tipo de objeto.Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. Para elementos de tipo de referência, esse valor é null.For reference-type elements, this value is null. Para elementos de tipo de valor, esse valor é 0, 0,0, ou false, dependendo do tipo de elemento específico.For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.

Retornos

Um objeto que contém o valor retornado do método invocado, ou null no caso de um construtor.An object containing the return value of the invoked method, or null in the case of a constructor.

Implementações

Exceções

Em vez disso, no .NET para aplicativos da Windows Store ou na Biblioteca de Classes Portátil, verifique Exception.In the.NET for Windows Store apps or the Portable Class Library, catch Exception instead.

O parâmetro obj é null e o método não é estático.The obj parameter is null and the method is not static. - ou --or- O método não está declarado nem é herdado pela classe de obj.The method is not declared or inherited by the class of obj. - ou --or- Um construtor estático é invocado, e obj não é null nem uma instância da classe que declarou o construtor.A static constructor is invoked, and obj is neither null nor an instance of the class that declared the constructor.

Os elementos da matriz parameters não correspondem à assinatura do método ou do construtor refletida por essa instância.The elements of the parameters array do not match the signature of the method or constructor reflected by this instance.

O método ou o construtor invocado gera uma exceção.The invoked method or constructor throws an exception.

- ou --or- A instância atual é um DynamicMethod que contém um código não verificável.The current instance is a DynamicMethod that contains unverifiable code. Consulte a seção “Verificação” em Comentários de DynamicMethod.See the "Verification" section in Remarks for DynamicMethod.

A matriz parameters não tem o número correto de argumentos.The parameters array does not have the correct number of arguments.

Em vez disso, no .NET para aplicativos da Windows Store ou na Biblioteca de Classes Portátil, capture a exceção de classe base, MemberAccessException.In the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

O chamador não tem permissão para executar o método ou um construtor representado pela instância atual.The caller does not have permission to execute the method or constructor that is represented by the current instance.

O tipo que declara o método é um tipo genérico aberto.The type that declares the method is an open generic type. Ou seja, a propriedade ContainsGenericParameters retorna true para o tipo declarativo.That is, the ContainsGenericParameters property returns true for the declaring type.

A instância atual é um MethodBuilder.The current instance is a MethodBuilder.

Exemplos

O exemplo de código a seguir demonstra a pesquisa de métodos dinâmicos usando reflexão.The following code example demonstrates dynamic method lookup using reflection. Observe que você não pode usar MethodInfo o objeto da classe base para invocar o método substituído na classe derivada, pois a associação tardia não pode resolver substituições.Note that you cannot use the MethodInfo object from the base class to invoke the overridden method in the derived class, because late binding cannot resolve overrides.

using namespace System;
using namespace System::Reflection;

public ref class MagicClass
{
private:
    int magicBaseValue;

public:
    MagicClass()
    {
        magicBaseValue = 9;
    }

    int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
};

public ref class TestMethodInfo
{
public:
    static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type^ magicType = Type::GetType("MagicClass");
        ConstructorInfo^ magicConstructor = magicType->GetConstructor(Type::EmptyTypes);
        Object^ magicClassObject = magicConstructor->Invoke(gcnew array<Object^>(0));

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo^ magicMethod = magicType->GetMethod("ItsMagic");
        Object^ magicValue = magicMethod->Invoke(magicClassObject, gcnew array<Object^>(1){100});

        Console::WriteLine("MethodInfo.Invoke() Example\n");
        Console::WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
};

int main()
{
    TestMethodInfo::Main();
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900
using System;
using System.Reflection;

public class MagicClass
{
    private int magicBaseValue;

    public MagicClass()
    {
        magicBaseValue = 9;
    }
    
    public int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
}

public class TestMethodInfo
{
    public static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type magicType = Type.GetType("MagicClass");
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
        object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

        Console.WriteLine("MethodInfo.Invoke() Example\n");
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900
Imports System.Reflection

Public Class MagicClass
    Private magicBaseValue As Integer

    Public Sub New()
        magicBaseValue = 9
    End Sub

    Public Function ItsMagic(preMagic As Integer) As Integer
        Return preMagic * magicBaseValue
    End Function
End Class

Public Class TestMethodInfo
    Public Shared Sub Main()
        ' Get the constructor and create an instance of MagicClass

        Dim magicType As Type = Type.GetType("MagicClass")
        Dim magicConstructor As ConstructorInfo = magicType.GetConstructor(Type.EmptyTypes)
        Dim magicClassObject As Object = magicConstructor.Invoke(New Object(){})

        ' Get the ItsMagic method and invoke with a parameter value of 100

        Dim magicMethod As MethodInfo = magicType.GetMethod("ItsMagic")
        Dim magicValue As Object = magicMethod.Invoke(magicClassObject, New Object(){100})

        Console.WriteLine("MethodInfo.Invoke() Example" + vbNewLine)
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue)
    End Sub
End Class

' The example program gives the following output:
'
' MethodInfo.Invoke() Example
'
' MagicClass.ItsMagic() returned: 900

Comentários

Esse é um método de conveniência que chama Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) a sobrecarga do método Default , invokeAttr passando null para binder e culturepara e.This is a convenience method that calls the Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) method overload, passing Default for invokeAttr and null for binder and culture.

Se o método invocado lançar uma exceção, Exception.GetBaseException o método retornará a exceção.If the invoked method throws an exception, the Exception.GetBaseException method returns the exception.

Para invocar um método estático usando MethodInfo seu objeto, null passe objpara.To invoke a static method using its MethodInfo object, pass null for obj.

Observação

Se essa sobrecarga de método for usada para invocar um construtor de instância, o obj objeto fornecido para será reinicializado; ou seja, todos os inicializadores de instância serão executados.If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. O valor retornado é null.The return value is null. Se um construtor de classe for invocado, a classe será reinicializada; ou seja, todos os inicializadores de classe são executados.If a class constructor is invoked, the class is reinitialized; that is, all class initializers are executed. O valor retornado é null.The return value is null.

Observação

A partir do .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, esse método pode ser usado para acessar membros não públicos se o chamador tiver sido concedido ReflectionPermission com o ReflectionPermissionFlag.RestrictedMemberAccess sinalizador e se o conjunto de concessão dos membros não públicos for restrito ao conjunto de concessão do chamador ou a um subconjunto dele.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (Consulte considerações de segurança para reflexão.)(See Security Considerations for Reflection.)

Para usar essa funcionalidade, seu aplicativo deve ser direcionado ao .NET Framework 3,5.NET Framework 3.5 ou posterior.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Se um parâmetro do método atual for um tipo de valor e o argumento correspondente em parameters for null, o tempo de execução passará uma instância de inicialização zero do tipo de valor.If a parameter of the current method is a value type, and the corresponding argument in parameters is null, the runtime passes a zero-initialized instance of the value type.

Segurança

ReflectionPermission
quando invocado com associação tardia por meio de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeração associada: MemberAccess.Associated enumeration: MemberAccess.

Veja também

Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Quando substituído em uma classe derivada, invoca o método ou o construtor refletido com parâmetros especificados.When overridden in a derived class, invokes the reflected method or constructor with the given parameters.

public:
 abstract System::Object ^ Invoke(System::Object ^ obj, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ parameters, System::Globalization::CultureInfo ^ culture);
public abstract object Invoke (object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture);
abstract member Invoke : obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj

Parâmetros

obj
Object

O objeto no qual o método ou o construtor será invocado.The object on which to invoke the method or constructor. Se um método for estático, esse argumento será ignorado.If a method is static, this argument is ignored. Se um construtor for estático, esse argumento deverá ser null ou uma instância da classe que define o construtor.If a constructor is static, this argument must be null or an instance of the class that defines the constructor.

invokeAttr
BindingFlags

Um bitmask que é uma combinação de 0 ou mais sinalizadores de bit de BindingFlags.A bitmask that is a combination of 0 or more bit flags from BindingFlags. Se binder for null, este parâmetro receberá o valor Default; portanto, tudo o que você passar será ignorado.If binder is null, this parameter is assigned the value Default; thus, whatever you pass in is ignored.

binder
Binder

Um objeto que permite a associação, a coerção de tipos de argumentos, invocação de membros e a recuperação de objetos MemberInfo por meio de reflexão.An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects via reflection. Caso binder seja null, o associador padrão é usado.If binder is null, the default binder is used.

parameters
Object[]

Uma lista de argumentos para o construtor ou método invocado.An argument list for the invoked method or constructor. Esta é uma matriz de objetos com o mesmo número, ordem e tipo que os parâmetros do método ou do construtor a ser invocado.This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. Se não houver nenhum parâmetro, isso deverá ser null.If there are no parameters, this should be null.

Se o método ou construtor representado por esta instância usar um parâmetro ByRef, não será necessário nenhum atributo especial para esse parâmetro a fim de invocar o método ou o construtor que usa essa função.If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. Qualquer objeto nesta matriz que não for inicializado explicitamente com um valor conterá o valor padrão desse tipo de objeto.Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. Para elementos de tipo de referência, esse valor é null.For reference-type elements, this value is null. Para elementos de tipo de valor, esse valor é 0, 0,0, ou false, dependendo do tipo de elemento específico.For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.

culture
CultureInfo

Uma instância de CultureInfo usada para determinar a coerção de tipos.An instance of CultureInfo used to govern the coercion of types. Se isso for null, será usado o CultureInfo para o thread atual.If this is null, the CultureInfo for the current thread is used. (Isso é necessário para converter um String que representa 1000 para um valor Double, por exemplo, uma vez que 1000 é representado de forma diferente por diferentes culturas.)(This is necessary to convert a String that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)

Retornos

Um Object que contém o valor retornado do método invocado, ou null, no caso de um construtor, ou null, se o tipo de retorno do método for void.An Object containing the return value of the invoked method, or null in the case of a constructor, or null if the method's return type is void. Antes de chamar o método ou o construtor, o Invoke verifica se o usuário tem permissão de acesso e verifica se os parâmetros são válidos.Before calling the method or constructor, Invoke checks to see if the user has access permission and verifies that the parameters are valid.

Implementações

Exceções

O parâmetro obj é null e o método não é estático.The obj parameter is null and the method is not static.

- ou --or- O método não está declarado nem é herdado pela classe de obj.The method is not declared or inherited by the class of obj.

- ou --or- Um construtor estático é invocado, e obj não é null nem uma instância da classe que declarou o construtor.A static constructor is invoked, and obj is neither null nor an instance of the class that declared the constructor.

O tipo do parâmetro parameters não corresponde à assinatura do método ou do construtor refletida por essa instância.The type of the parameters parameter does not match the signature of the method or constructor reflected by this instance.

A matriz parameters não tem o número correto de argumentos.The parameters array does not have the correct number of arguments.

O método ou o construtor invocado gera uma exceção.The invoked method or constructor throws an exception.

O chamador não tem permissão para executar o método ou um construtor representado pela instância atual.The caller does not have permission to execute the method or constructor that is represented by the current instance.

O tipo que declara o método é um tipo genérico aberto.The type that declares the method is an open generic type. Ou seja, a propriedade ContainsGenericParameters retorna true para o tipo declarativo.That is, the ContainsGenericParameters property returns true for the declaring type.

Exemplos

O exemplo a seguir demonstra todos os membros System.Reflection.Binder da classe usando uma sobrecarga Type.InvokeMemberde.The following example demonstrates all members of the System.Reflection.Binder class using an overload of Type.InvokeMember. O método CanConvertFrom particular localiza tipos compatíveis para um determinado tipo.The private method CanConvertFrom finds compatible types for a given type. Para obter outro exemplo de invocar Membros em um cenário de ligação personalizada, consulte carregando e usando tipos dinamicamente.For another example of invoking members in a custom binding scenario, see Dynamically Loading and Using Types.

using namespace System;
using namespace System::Reflection;
using namespace System::Globalization;
using namespace System::Runtime::InteropServices;
public ref class MyBinder: public Binder
{
public:
   MyBinder()
      : Binder()
   {}

private:
   ref class BinderState
   {
   public:
      array<Object^>^args;
   };

public:
   virtual FieldInfo^ BindToField( BindingFlags bindingAttr, array<FieldInfo^>^match, Object^ value, CultureInfo^ culture ) override
   {
      if ( match == nullptr )
            throw gcnew ArgumentNullException( "match" );

      // Get a field for which the value parameter can be converted to the specified field type.
      for ( int i = 0; i < match->Length; i++ )
         if ( ChangeType( value, match[ i ]->FieldType, culture ) != nullptr )
                  return match[ i ];

      return nullptr;
   }

   virtual MethodBase^ BindToMethod( BindingFlags bindingAttr, array<MethodBase^>^match, array<Object^>^%args, array<ParameterModifier>^ modifiers, CultureInfo^ culture, array<String^>^names, [Out]Object^% state ) override
   {
      // Store the arguments to the method in a state Object*.
      BinderState^ myBinderState = gcnew BinderState;
      array<Object^>^arguments = gcnew array<Object^>(args->Length);
      args->CopyTo( arguments, 0 );
      myBinderState->args = arguments;
      state = myBinderState;
      if ( match == nullptr )
            throw gcnew ArgumentNullException;

      // Find a method that has the same parameters as those of the args parameter.
      for ( int i = 0; i < match->Length; i++ )
      {
         // Count the number of parameters that match.
         int count = 0;
         array<ParameterInfo^>^parameters = match[ i ]->GetParameters();

         // Go on to the next method if the number of parameters do not match.
         if ( args->Length != parameters->Length )
                  continue;

         // Match each of the parameters that the user expects the method to have.
         for ( int j = 0; j < args->Length; j++ )
         {
            // If the names parameter is not 0, then reorder args.
            if ( names != nullptr )
            {
               if ( names->Length != args->Length )
                              throw gcnew ArgumentException( "names and args must have the same number of elements." );

               for ( int k = 0; k < names->Length; k++ )
                  if ( String::Compare( parameters[ j ]->Name, names[ k ] ) == 0 )
                                    args[ j ] = myBinderState->args[ k ];
            }

            // Determine whether the types specified by the user can be converted to the parameter type.
            if ( ChangeType( args[ j ], parameters[ j ]->ParameterType, culture ) != nullptr )
                        count += 1;
            else
                        break;
         }
         if ( count == args->Length )
                  return match[ i ];
      }
      return nullptr;
   }

   virtual Object^ ChangeType( Object^ value, Type^ myChangeType, CultureInfo^ culture ) override
   {
      // Determine whether the value parameter can be converted to a value of type myType.
      if ( CanConvertFrom( value->GetType(), myChangeType ) )
         // Return the converted Object*.
         return Convert::ChangeType( value, myChangeType ); 
      else
         return nullptr;
   }

   virtual void ReorderArgumentArray( array<Object^>^%args, Object^ state ) override
   {
      // Return the args that had been reordered by BindToMethod.
      (safe_cast<BinderState^>(state))->args->CopyTo( args, 0 );
   }

   virtual MethodBase^ SelectMethod( BindingFlags bindingAttr, array<MethodBase^>^match, array<Type^>^types, array<ParameterModifier>^ modifiers ) override
   {
      if ( match == nullptr )
            throw gcnew ArgumentNullException( "match" );

      for ( int i = 0; i < match->Length; i++ )
      {
         // Count the number of parameters that match.
         int count = 0;
         array<ParameterInfo^>^parameters = match[ i ]->GetParameters();

         // Go on to the next method if the number of parameters do not match.
         if ( types->Length != parameters->Length )
                  continue;

         // Match each of the parameters that the user expects the method to have.
         for ( int j = 0; j < types->Length; j++ )
         {
            // Determine whether the types specified by the user can be converted to parameter type.
            if ( CanConvertFrom( types[ j ], parameters[ j ]->ParameterType ) )
                        count += 1;
            else
                        break;
         }
         // Determine whether the method has been found.
         if ( count == types->Length )
                  return match[ i ];
      }
      return nullptr;
   }

   virtual PropertyInfo^ SelectProperty( BindingFlags bindingAttr, array<PropertyInfo^>^match, Type^ returnType, array<Type^>^indexes, array<ParameterModifier>^ modifiers ) override
   {
      if ( match == nullptr )
            throw gcnew ArgumentNullException( "match" );

      for ( int i = 0; i < match->Length; i++ )
      {
         // Count the number of indexes that match.
         int count = 0;
         array<ParameterInfo^>^parameters = match[ i ]->GetIndexParameters();

         // Go on to the next property if the number of indexes do not match.
         if ( indexes->Length != parameters->Length )
                  continue;

         // Match each of the indexes that the user expects the property to have.
         for ( int j = 0; j < indexes->Length; j++ )
            // Determine whether the types specified by the user can be converted to index type.
            if ( CanConvertFrom( indexes[ j ], parameters[ j ]->ParameterType ) )
                        count += 1;
            else
                        break;

         // Determine whether the property has been found.
         if ( count == indexes->Length )
         {
            // Determine whether the return type can be converted to the properties type.
            if ( CanConvertFrom( returnType, match[ i ]->PropertyType ) )
                  return match[ i ];
            else
                  continue;
         }
      }
      return nullptr;
   }

private:

   // Determines whether type1 can be converted to type2. Check only for primitive types.
   bool CanConvertFrom( Type^ type1, Type^ type2 )
   {
      if ( type1->IsPrimitive && type2->IsPrimitive )
      {
         TypeCode typeCode1 = Type::GetTypeCode( type1 );
         TypeCode typeCode2 = Type::GetTypeCode( type2 );

         // If both type1 and type2 have the same type, return true.
         if ( typeCode1 == typeCode2 )
                  return true;

         // Possible conversions from Char follow.
         if ( typeCode1 == TypeCode::Char )
         {
            switch ( typeCode2 )
            {
               case TypeCode::UInt16:
                  return true;

               case TypeCode::UInt32:
                  return true;

               case TypeCode::Int32:
                  return true;

               case TypeCode::UInt64:
                  return true;

               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from Byte follow.
         if ( typeCode1 == TypeCode::Byte )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Char:
                  return true;

               case TypeCode::UInt16:
                  return true;

               case TypeCode::Int16:
                  return true;

               case TypeCode::UInt32:
                  return true;

               case TypeCode::Int32:
                  return true;

               case TypeCode::UInt64:
                  return true;

               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from SByte follow.
         if ( typeCode1 == TypeCode::SByte )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Int16:
                  return true;

               case TypeCode::Int32:
                  return true;

               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from UInt16 follow.
         if ( typeCode1 == TypeCode::UInt16 )
         {
            switch ( typeCode2 )
            {
               case TypeCode::UInt32:
                  return true;

               case TypeCode::Int32:
                  return true;

               case TypeCode::UInt64:
                  return true;

               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from Int16 follow.
         if ( typeCode1 == TypeCode::Int16 )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Int32:
                  return true;

               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from UInt32 follow.
         if ( typeCode1 == TypeCode::UInt32 )
         {
            switch ( typeCode2 )
            {
               case TypeCode::UInt64:
                  return true;

               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from Int32 follow.
         if ( typeCode1 == TypeCode::Int32 )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Int64:
                  return true;

               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from UInt64 follow.
         if ( typeCode1 == TypeCode::UInt64 )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from Int64 follow.
         if ( typeCode1 == TypeCode::Int64 )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Single:
                  return true;

               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }

         // Possible conversions from Single follow.
         if ( typeCode1 == TypeCode::Single )
         {
            switch ( typeCode2 )
            {
               case TypeCode::Double:
                  return true;

               default:
                  return false;
            }
         }
      }

      return false;
   }

};

public ref class MyClass1
{
public:
   short myFieldB;
   int myFieldA;
   void MyMethod( long i, char k )
   {
      Console::WriteLine( "\nThis is MyMethod(long i, char k)" );
   }

   void MyMethod( long i, long j )
   {
      Console::WriteLine( "\nThis is MyMethod(long i, long j)" );
   }
};

int main()
{
   // Get the type of MyClass1.
   Type^ myType = MyClass1::typeid;

   // Get the instance of MyClass1.
   MyClass1^ myInstance = gcnew MyClass1;
   Console::WriteLine( "\nDisplaying the results of using the MyBinder binder.\n" );

   // Get the method information for MyMethod.
   array<Type^>^types = {short::typeid,short::typeid};
   MethodInfo^ myMethod = myType->GetMethod( "MyMethod", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance), gcnew MyBinder, types, nullptr );
   Console::WriteLine( myMethod );

   // Invoke MyMethod.
   array<Object^>^obj = {32,32};
   myMethod->Invoke( myInstance, BindingFlags::InvokeMethod, gcnew MyBinder, obj, CultureInfo::CurrentCulture );
}
using System;
using System.Reflection;
using System.Globalization;

public class MyBinder : Binder 
{
    public MyBinder() : base()
    {
    }
    private class BinderState
    {
        public object[] args;
    }
    public override FieldInfo BindToField(
        BindingFlags bindingAttr,
        FieldInfo[] match,
        object value,
        CultureInfo culture
        )
    {
        if(match == null)
            throw new ArgumentNullException("match");
        // Get a field for which the value parameter can be converted to the specified field type.
        for(int i = 0; i < match.Length; i++)
            if(ChangeType(value, match[i].FieldType, culture) != null)
                return match[i];
        return null;
    }
    public override MethodBase BindToMethod(
        BindingFlags bindingAttr,
        MethodBase[] match,
        ref object[] args,
        ParameterModifier[] modifiers,
        CultureInfo culture,
        string[] names,
        out object state
        )
    {
        // Store the arguments to the method in a state object.
        BinderState myBinderState = new BinderState();
        object[] arguments = new Object[args.Length];
        args.CopyTo(arguments, 0);
        myBinderState.args = arguments;
        state = myBinderState;
        if(match == null)
            throw new ArgumentNullException();
        // Find a method that has the same parameters as those of the args parameter.
        for(int i = 0; i < match.Length; i++)
        {
            // Count the number of parameters that match.
            int count = 0;
            ParameterInfo[] parameters = match[i].GetParameters();
            // Go on to the next method if the number of parameters do not match.
            if(args.Length != parameters.Length)
                continue;
            // Match each of the parameters that the user expects the method to have.
            for(int j = 0; j < args.Length; j++)
            {
                // If the names parameter is not null, then reorder args.
                if(names != null)
                {
                    if(names.Length != args.Length)
                        throw new ArgumentException("names and args must have the same number of elements.");
                    for(int k = 0; k < names.Length; k++)
                        if(String.Compare(parameters[j].Name, names[k].ToString()) == 0)
                            args[j] = myBinderState.args[k];
                }
                // Determine whether the types specified by the user can be converted to the parameter type.
                if(ChangeType(args[j], parameters[j].ParameterType, culture) != null)
                    count += 1;
                else
                    break;
            }
            // Determine whether the method has been found.
            if(count == args.Length)
                return match[i];
        }
        return null;
    }
    public override object ChangeType(
        object value,
        Type myChangeType,
        CultureInfo culture
        )
    {
        // Determine whether the value parameter can be converted to a value of type myType.
        if(CanConvertFrom(value.GetType(), myChangeType))
            // Return the converted object.
            return Convert.ChangeType(value, myChangeType);
        else
            // Return null.
            return null;
    }
    public override void ReorderArgumentArray(
        ref object[] args,
        object state
        )
    {
        // Return the args that had been reordered by BindToMethod.
        ((BinderState)state).args.CopyTo(args, 0);
    }
    public override MethodBase SelectMethod(
        BindingFlags bindingAttr,
        MethodBase[] match,
        Type[] types,
        ParameterModifier[] modifiers
        )
    {
        if(match == null)
            throw new ArgumentNullException("match");
        for(int i = 0; i < match.Length; i++)
        {
            // Count the number of parameters that match.
            int count = 0; 
            ParameterInfo[] parameters = match[i].GetParameters();
            // Go on to the next method if the number of parameters do not match.
            if(types.Length != parameters.Length)
                continue;
            // Match each of the parameters that the user expects the method to have.
            for(int j = 0; j < types.Length; j++)
                // Determine whether the types specified by the user can be converted to parameter type.
                if(CanConvertFrom(types[j], parameters[j].ParameterType))
                    count += 1;
                else
                    break;
            // Determine whether the method has been found.
            if(count == types.Length)
                return match[i];
        }
        return null;
    }
    public override PropertyInfo SelectProperty(
        BindingFlags bindingAttr,
        PropertyInfo[] match,
        Type returnType,
        Type[] indexes,
        ParameterModifier[] modifiers
        )
    {
        if(match == null)
            throw new ArgumentNullException("match");
        for(int i = 0; i < match.Length; i++)
        {
            // Count the number of indexes that match.
            int count = 0;
            ParameterInfo[] parameters = match[i].GetIndexParameters();
            // Go on to the next property if the number of indexes do not match.
            if(indexes.Length != parameters.Length)
                continue;
            // Match each of the indexes that the user expects the property to have.
            for(int j = 0; j < indexes.Length; j++)
                // Determine whether the types specified by the user can be converted to index type.
                if(CanConvertFrom(indexes[j], parameters[j].ParameterType))
                    count += 1;
                else
                    break;
            // Determine whether the property has been found.
            if(count == indexes.Length)
                // Determine whether the return type can be converted to the properties type.
                if(CanConvertFrom(returnType, match[i].PropertyType))
                    return match[i];
                else
                    continue;
        }
        return null;
    }
    // Determines whether type1 can be converted to type2. Check only for primitive types.
    private bool CanConvertFrom(Type type1, Type type2)
    {
        if(type1.IsPrimitive && type2.IsPrimitive)
        {
            TypeCode typeCode1 = Type.GetTypeCode(type1);
            TypeCode typeCode2 = Type.GetTypeCode(type2);
            // If both type1 and type2 have the same type, return true.
            if(typeCode1 == typeCode2)
                return true;
            // Possible conversions from Char follow.
            if(typeCode1 == TypeCode.Char)
                switch(typeCode2)
                {
                    case TypeCode.UInt16 : return true;
                    case TypeCode.UInt32 : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Byte follow.
            if(typeCode1 == TypeCode.Byte)
                switch(typeCode2)
                {
                    case TypeCode.Char   : return true;
                    case TypeCode.UInt16 : return true;
                    case TypeCode.Int16  : return true;
                    case TypeCode.UInt32 : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from SByte follow.
            if(typeCode1 == TypeCode.SByte)
                switch(typeCode2)
                {
                    case TypeCode.Int16  : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from UInt16 follow.
            if(typeCode1 == TypeCode.UInt16)
                switch(typeCode2)
                {
                    case TypeCode.UInt32 : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Int16 follow.
            if(typeCode1 == TypeCode.Int16)
                switch(typeCode2)
                {
                    case TypeCode.Int32  : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from UInt32 follow.
            if(typeCode1 == TypeCode.UInt32)
                switch(typeCode2)
                {
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Int32 follow.
            if(typeCode1 == TypeCode.Int32)
                switch(typeCode2)
                {
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from UInt64 follow.
            if(typeCode1 == TypeCode.UInt64)
                switch(typeCode2)
                {
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Int64 follow.
            if(typeCode1 == TypeCode.Int64)
                switch(typeCode2)
                {
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Single follow.
            if(typeCode1 == TypeCode.Single)
                switch(typeCode2)
                {
                    case TypeCode.Double : return true;
                    default              : return false;
                }
        }
        return false;
    }
}
public class MyClass1
{
    public short myFieldB;
    public int myFieldA; 
    public void MyMethod(long i, char k)
    {
        Console.WriteLine("\nThis is MyMethod(long i, char k)");
    }
    public void MyMethod(long i, long j)
    {
        Console.WriteLine("\nThis is MyMethod(long i, long j)");
    }
}
public class Binder_Example
{
    public static void Main()
    {
        // Get the type of MyClass1.
        Type myType = typeof(MyClass1);
        // Get the instance of MyClass1.
        MyClass1 myInstance = new MyClass1();
        Console.WriteLine("\nDisplaying the results of using the MyBinder binder.\n");
        // Get the method information for MyMethod.
        MethodInfo myMethod = myType.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance,
            new MyBinder(), new Type[] {typeof(short), typeof(short)}, null);
        Console.WriteLine(myMethod);
        // Invoke MyMethod.
        myMethod.Invoke(myInstance, BindingFlags.InvokeMethod, new MyBinder(), new Object[] {(int)32, (int)32}, CultureInfo.CurrentCulture);
    }
}
Imports System.Reflection
Imports System.Globalization

Public Class MyBinder
    Inherits Binder
    Public Sub New()
        MyBase.new()
    End Sub
    Private Class BinderState
        Public args() As Object
    End Class

    Public Overrides Function BindToField(ByVal bindingAttr As BindingFlags, ByVal match() As FieldInfo, ByVal value As Object, ByVal culture As CultureInfo) As FieldInfo
        If match Is Nothing Then
            Throw New ArgumentNullException("match")
        End If
        ' Get a field for which the value parameter can be converted to the specified field type.
        Dim i As Integer
        For i = 0 To match.Length - 1
            If Not (ChangeType(value, match(i).FieldType, culture) Is Nothing) Then
                Return match(i)
            End If
        Next i
        Return Nothing
    End Function 'BindToField

    Public Overrides Function BindToMethod(ByVal bindingAttr As BindingFlags, ByVal match() As MethodBase, ByRef args() As Object, ByVal modifiers() As ParameterModifier, ByVal culture As CultureInfo, ByVal names() As String, ByRef state As Object) As MethodBase
        ' Store the arguments to the method in a state object.
        Dim myBinderState As New BinderState()
        Dim arguments() As Object = New [Object](args.Length) {}
        args.CopyTo(arguments, 0)
        myBinderState.args = arguments
        state = myBinderState

        If match Is Nothing Then
            Throw New ArgumentNullException()
        End If
        ' Find a method that has the same parameters as those of args.
        Dim i As Integer
        For i = 0 To match.Length - 1
            ' Count the number of parameters that match.
            Dim count As Integer = 0
            Dim parameters As ParameterInfo() = match(i).GetParameters()
            ' Go on to the next method if the number of parameters do not match.
            If args.Length <> parameters.Length Then
                GoTo ContinueFori
            End If
            ' Match each of the parameters that the user expects the method to have.
            Dim j As Integer
            For j = 0 To args.Length - 1
                ' If names is not null, then reorder args.
                If Not (names Is Nothing) Then
                    If names.Length <> args.Length Then
                        Throw New ArgumentException("names and args must have the same number of elements.")
                    End If
                    Dim k As Integer
                    For k = 0 To names.Length - 1
                        If String.Compare(parameters(j).Name, names(k).ToString()) = 0 Then
                            args(j) = myBinderState.args(k)
                        End If
                    Next k
                End If ' Determine whether the types specified by the user can be converted to parameter type.
                If Not (ChangeType(args(j), parameters(j).ParameterType, culture) Is Nothing) Then
                    count += 1
                Else
                    Exit For
                End If
            Next j
            ' Determine whether the method has been found.
            If count = args.Length Then
                Return match(i)
            End If
ContinueFori:
        Next i
        Return Nothing
    End Function 'BindToMethod

    Public Overrides Function ChangeType(ByVal value As Object, ByVal myChangeType As Type, ByVal culture As CultureInfo) As Object
        ' Determine whether the value parameter can be converted to a value of type myType.
        If CanConvertFrom(value.GetType(), myChangeType) Then
            ' Return the converted object.
            Return Convert.ChangeType(value, myChangeType)
            ' Return null.
        Else
            Return Nothing
        End If
    End Function 'ChangeType

    Public Overrides Sub ReorderArgumentArray(ByRef args() As Object, ByVal state As Object)
        'Redimension the array to hold the state values.
        ReDim args(CType(state, BinderState).args.Length)
        ' Return the args that had been reordered by BindToMethod.
        CType(state, BinderState).args.CopyTo(args, 0)
    End Sub

    Public Overrides Function SelectMethod(ByVal bindingAttr As BindingFlags, ByVal match() As MethodBase, ByVal types() As Type, ByVal modifiers() As ParameterModifier) As MethodBase
        If match Is Nothing Then
            Throw New ArgumentNullException("match")
        End If
        Dim i As Integer
        For i = 0 To match.Length - 1
            ' Count the number of parameters that match.
            Dim count As Integer = 0
            Dim parameters As ParameterInfo() = match(i).GetParameters()
            ' Go on to the next method if the number of parameters do not match.
            If types.Length <> parameters.Length Then
                GoTo ContinueFori
            End If
            ' Match each of the parameters that the user expects the method to have.
            Dim j As Integer
            For j = 0 To types.Length - 1
                ' Determine whether the types specified by the user can be converted to parameter type.
                If CanConvertFrom(types(j), parameters(j).ParameterType) Then
                    count += 1
                Else
                    Exit For
                End If
            Next j ' Determine whether the method has been found.
            If count = types.Length Then
                Return match(i)
            End If
ContinueFori:
        Next i
        Return Nothing
    End Function 'SelectMethod
    Public Overrides Function SelectProperty(ByVal bindingAttr As BindingFlags, ByVal match() As PropertyInfo, ByVal returnType As Type, ByVal indexes() As Type, ByVal modifiers() As ParameterModifier) As PropertyInfo
        If match Is Nothing Then
            Throw New ArgumentNullException("match")
        End If
        Dim i As Integer
        For i = 0 To match.Length - 1
            ' Count the number of indexes that match.
            Dim count As Integer = 0
            Dim parameters As ParameterInfo() = match(i).GetIndexParameters()

            ' Go on to the next property if the number of indexes do not match.
            If indexes.Length <> parameters.Length Then
                GoTo ContinueFori
            End If
            ' Match each of the indexes that the user expects the property to have.
            Dim j As Integer
            For j = 0 To indexes.Length - 1
                ' Determine whether the types specified by the user can be converted to index type.
                If CanConvertFrom(indexes(j), parameters(j).ParameterType) Then
                    count += 1
                Else
                    Exit For
                End If
            Next j ' Determine whether the property has been found.
            If count = indexes.Length Then
                ' Determine whether the return type can be converted to the properties type.
                If CanConvertFrom(returnType, match(i).PropertyType) Then
                    Return match(i)
                Else
                    GoTo ContinueFori
                End If
            End If
ContinueFori:
        Next i
        Return Nothing
    End Function 'SelectProperty

    ' Determine whether type1 can be converted to type2. Check only for primitive types.
    Private Function CanConvertFrom(ByVal type1 As Type, ByVal type2 As Type) As Boolean
        If type1.IsPrimitive And type2.IsPrimitive Then
            Dim typeCode1 As TypeCode = Type.GetTypeCode(type1)
            Dim typeCode2 As TypeCode = Type.GetTypeCode(type2)
            ' If both type1 and type2 have same type, return true.
            If typeCode1 = typeCode2 Then
                Return True
            End If ' Possible conversions from Char follow.
            If typeCode1 = TypeCode.Char Then
                Select Case typeCode2
                    Case TypeCode.UInt16
                        Return True
                    Case TypeCode.UInt32
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Byte follow.
            If typeCode1 = TypeCode.Byte Then
                Select Case typeCode2
                    Case TypeCode.Char
                        Return True
                    Case TypeCode.UInt16
                        Return True
                    Case TypeCode.Int16
                        Return True
                    Case TypeCode.UInt32
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from SByte follow.
            If typeCode1 = TypeCode.SByte Then
                Select Case typeCode2
                    Case TypeCode.Int16
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from UInt16 follow.
            If typeCode1 = TypeCode.UInt16 Then
                Select Case typeCode2
                    Case TypeCode.UInt32
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Int16 follow.
            If typeCode1 = TypeCode.Int16 Then
                Select Case typeCode2
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from UInt32 follow.
            If typeCode1 = TypeCode.UInt32 Then
                Select Case typeCode2
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Int32 follow.
            If typeCode1 = TypeCode.Int32 Then
                Select Case typeCode2
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from UInt64 follow.
            If typeCode1 = TypeCode.UInt64 Then
                Select Case typeCode2
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Int64 follow.
            If typeCode1 = TypeCode.Int64 Then
                Select Case typeCode2
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Single follow.
            If typeCode1 = TypeCode.Single Then
                Select Case typeCode2
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If
        End If
        Return False
    End Function 'CanConvertFrom
End Class


Public Class MyClass1
    Public myFieldB As Short
    Public myFieldA As Integer

    Public Overloads Sub MyMethod(ByVal i As Long, ByVal k As Char)
        Console.WriteLine(ControlChars.NewLine & "This is MyMethod(long i, char k).")
    End Sub

    Public Overloads Sub MyMethod(ByVal i As Long, ByVal j As Long)
        Console.WriteLine(ControlChars.NewLine & "This is MyMethod(long i, long j).")
    End Sub
End Class


Public Class Binder_Example
    Public Shared Sub Main()
        ' Get the type of MyClass1.
        Dim myType As Type = GetType(MyClass1)
        ' Get the instance of MyClass1.
        Dim myInstance As New MyClass1()
        Console.WriteLine(ControlChars.Cr & "Displaying the results of using the MyBinder binder.")
        Console.WriteLine()
        ' Get the method information for MyMethod.
        Dim myMethod As MethodInfo = myType.GetMethod("MyMethod", BindingFlags.Public Or BindingFlags.Instance, New MyBinder(), New Type() {GetType(Short), GetType(Short)}, Nothing)
        Console.WriteLine(MyMethod)
        ' Invoke MyMethod.
        myMethod.Invoke(myInstance, BindingFlags.InvokeMethod, New MyBinder(), New [Object]() {CInt(32), CInt(32)}, CultureInfo.CurrentCulture)
    End Sub
End Class

Comentários

Invoca dinamicamente o método refletido por essa instância em obje passa os parâmetros especificados.Dynamically invokes the method reflected by this instance on obj, and passes along the specified parameters. Se o método for estático, o obj parâmetro será ignorado.If the method is static, the obj parameter is ignored. Para métodos não estáticos, obj deve ser uma instância de uma classe que herda ou declara o método e deve ser do mesmo tipo que essa classe.For non-static methods, obj should be an instance of a class that inherits or declares the method and must be the same type as this class. Se o método não tiver parâmetros, o valor de parameters deverá ser null.If the method has no parameters, the value of parameters should be null. Caso contrário, o número, o tipo e a ordem dos parameters elementos em devem ser idênticos ao número, ao tipo e à ordem dos parâmetros para o método refletido por essa instância.Otherwise, the number, type, and order of elements in parameters should be identical to the number, type, and order of parameters for the method reflected by this instance.

Você não pode omitir parâmetros opcionais em Invokechamadas para.You may not omit optional parameters in calls to Invoke. Para invocar um método que omite parâmetros opcionais, você Type.InvokeMember deve chamar em vez disso.To invoke a method omitting optional parameters, you should call Type.InvokeMember instead.

Observação

Se essa sobrecarga de método for usada para invocar um construtor de instância, o obj objeto fornecido para será reinicializado; ou seja, todos os inicializadores de instância serão executados.If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. O valor retornado é null.The return value is null. Se um construtor de classe for invocado, a classe será reinicializada; ou seja, todos os inicializadores de classe são executados.If a class constructor is invoked, the class is reinitialized; that is, all class initializers are executed. O valor retornado é null.The return value is null.

Para parâmetros primitivos de passagem por valor, o alargamento normal é executado (Int16-> Int32, por exemplo).For pass-by-value primitive parameters, normal widening is performed (Int16 -> Int32, for example). Para parâmetros de referência de passagem por valor, o alargamento de referência normal é permitido (classe derivada para classe base e classe base para tipo de interface).For pass-by-value reference parameters, normal reference widening is allowed (derived class to base class, and base class to interface type). No entanto, para parâmetros primitivos de passagem por referência, os tipos devem corresponder exatamente.However, for pass-by-reference primitive parameters, the types must match exactly. Para parâmetros de referência de passagem por referência, o alargamento normal ainda se aplica.For pass-by-reference reference parameters, the normal widening still applies.

Por exemplo, se o método refletido por essa instância for declarado public boolean Compare(String a, String b)como parameters , deve ser uma matriz de Objects com comprimento 2 como parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2")essa.For example, if the method reflected by this instance is declared as public boolean Compare(String a, String b), then parameters should be an array of Objects with length 2 such that parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2").

Se um parâmetro do método atual for um tipo de valor e o argumento correspondente em parameters for null, o tempo de execução passará uma instância de inicialização zero do tipo de valor.If a parameter of the current method is a value type, and the corresponding argument in parameters is null, the runtime passes a zero-initialized instance of the value type.

A reflexão usa a pesquisa de método dinâmico ao invocar métodos virtuais.Reflection uses dynamic method lookup when invoking virtual methods. Por exemplo, suponha que a classe B herde da classe A e ambas implementem um método virtual chamado M. Agora suponha que você tenha um MethodInfo objeto que represente M na classe a. Se você usar o Invoke método para invocar M em um objeto do tipo B, a reflexão usará a implementação fornecida pela classe B. Mesmo que o objeto do tipo B seja convertido em a, a implementação fornecida pela classe B é usada (consulte o exemplo de código abaixo).For example, suppose that class B inherits from class A and both implement a virtual method named M. Now suppose that you have a MethodInfo object that represents M on class A. If you use the Invoke method to invoke M on an object of type B, then reflection will use the implementation given by class B. Even if the object of type B is cast to A, the implementation given by class B is used (see code sample below).

Por outro lado, se o método for não virtual, a reflexão usará a implementação fornecida pelo tipo do qual o MethodInfo foi obtido, independentemente do tipo do objeto passado como o destino.On the other hand, if the method is non-virtual, then reflection will use the implementation given by the type from which the MethodInfo was obtained, regardless of the type of the object passed as the target.

As restrições de acesso são ignoradas para código totalmente confiável.Access restrictions are ignored for fully trusted code. Ou seja, construtores particulares, métodos, campos e propriedades podem ser acessados e invocados por meio de reflexão sempre que o código é totalmente confiável.That is, private constructors, methods, fields, and properties can be accessed and invoked via reflection whenever the code is fully trusted.

Se o método invocado lançar uma exceção TargetInvocationException.GetException , o retornará a exceção.If the invoked method throws an exception, TargetInvocationException.GetException returns the exception. Essa implementação gera um NotSupportedException.This implementation throws a NotSupportedException.

Observação

A partir do .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, esse método pode ser usado para acessar membros não públicos se o chamador tiver sido concedido ReflectionPermission com o ReflectionPermissionFlag.RestrictedMemberAccess sinalizador e se o conjunto de concessão dos membros não públicos for restrito ao conjunto de concessão do chamador ou a um subconjunto dele.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (Consulte considerações de segurança para reflexão.)(See Security Considerations for Reflection.)

Para usar essa funcionalidade, seu aplicativo deve ser direcionado ao .NET Framework 3,5.NET Framework 3.5 ou posterior.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Segurança

ReflectionPermission
quando invocado com associação tardia por meio de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeração associada: MemberAccess.Associated enumeration: MemberAccess.

Veja também

Aplica-se a