IReflect.InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) Método

Definição

Invoca um membro especificado.Invokes a specified member.

public:
 System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args, cli::array <System::Reflection::ParameterModifier> ^ modifiers, System::Globalization::CultureInfo ^ culture, cli::array <System::String ^> ^ namedParameters);
public object? InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object? target, object?[]? args, System.Reflection.ParameterModifier[]? modifiers, System.Globalization.CultureInfo? culture, string[]? namedParameters);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Reflection.ParameterModifier[] * System.Globalization.CultureInfo * string[] -> obj
Public Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object(), modifiers As ParameterModifier(), culture As CultureInfo, namedParameters As String()) As Object

Parâmetros

name
String

O nome do membro a ser localizado.The name of the member to find.

invokeAttr
BindingFlags

Um dos atributos de invocação de BindingFlags.One of the BindingFlags invocation attributes. O parâmetro invokeAttr pode ser um construtor, um método, uma propriedade ou um campo.The invokeAttr parameter may be a constructor, method, property, or field. É necessário especificar um atributo de invocação adequado.A suitable invocation attribute must be specified. Invoque o membro padrão de uma classe, passando a cadeia de caracteres vazia ("") como o nome do membro.Invoke the default member of a class by passing the empty string ("") as the name of the member.

binder
Binder

Um dos sinalizadores de bit BindingFlags.One of the BindingFlags bit flags. Implementa Binder, contendo as propriedades relacionadas a este método.Implements Binder, containing properties related to this method.

target
Object

O objeto no qual invocar o membro especificado.The object on which to invoke the specified member. Esse parâmetro é ignorado para membros estáticos.This parameter is ignored for static members.

args
Object[]

Esta é uma matriz de objetos que contém o número, a ordem e o tipo dos parâmetros do membro a ser invocado.An array of objects that contains the number, order, and type of the parameters of the member to be invoked. Isso é uma matriz vazia se não há nenhum parâmetro.This is an empty array if there are no parameters.

modifiers
ParameterModifier[]

Uma matriz de objetos de ParameterModifier.An array of ParameterModifier objects. Essa matriz tem o mesmo tamanho que o parâmetro args que representa os atributos de argumento do membro invocado nos metadados.This array has the same length as the args parameter, representing the invoked member's argument attributes in the metadata. Um parâmetro pode ter os seguintes atributos: pdIn, pdOut, pdRetval, pdOptional e pdHasDefault.A parameter can have the following attributes: pdIn, pdOut, pdRetval, pdOptional, and pdHasDefault. Eles representam [In], [Out], [retval], [optional] e um parâmetro padrão, respectivamente.These represent [In], [Out], [retval], [optional], and a default parameter, respectively. Esses atributos são usados por diversos serviços de interoperabilidade.These attributes are used by various interoperability services.

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. Por exemplo, culture converte uma cadeia de caracteres que representa 1000 para um valor Double, uma vez que 1000 é representado de maneira diferente por diferentes culturas.For example, culture converts a string that represents 1000 to a Double value, since 1000 is represented differently by different cultures. Se esse parâmetro for null, será usado o CultureInfo para o thread atual.If this parameter is null, the CultureInfo for the current thread is used.

namedParameters
String[]

Uma matriz de cadeias de caracteres de parâmetros.A string array of parameters.

Retornos

Object

O membro especificado.The specified member.

Exceções

Mais de um argumento é especificado para um campo set.More than one argument is specified for a field set.

Não é possível encontrar o campo nem a propriedade.The field or property cannot be found.

Não é possível localizar o método.The method cannot be found.

Um membro privado é chamado sem a ReflectionPermission necessária.A private member is invoked without the necessary ReflectionPermission.

Exemplos

O exemplo a seguir obtém o valor da Now propriedade.The following example obtains the value of the Now property.

#using <System.DLL>

using namespace System;
using namespace System::Reflection;

#define NULL 0
void main()
{
   Type^ tDate = Type::GetType( L"System.DateTime" );
   Object^ result = tDate->InvokeMember( L"Now", BindingFlags::GetProperty, nullptr, NULL, gcnew array<Object^>(0) );
   Console::WriteLine( result->ToString() );
}

using System;
using System.Reflection;

public class MainClass
{
    public static void Main(string[] args)
    {
        Type tDate = typeof(System.DateTime);
        Object result = tDate.InvokeMember("Now",
            BindingFlags.GetProperty, null, null, new Object[0]);
        Console.WriteLine(result.ToString());
    }
}
Imports System.Reflection

Public Class MainClass
    Public Overloads Shared Sub Main(ByVal args() As String)
        Dim tDate As Type = GetType(System.DateTime)
        Dim result As [Object] = tDate.InvokeMember("Now", _
            BindingFlags.GetProperty, Nothing, Nothing, New [Object](-1) {})
        Console.WriteLine(result.ToString())
    End Sub
End Class

Comentários

O método a ser invocado deve ser acessível e fornecer a correspondência mais específica com a lista de argumentos especificada, sob as restrições dos atributos associadores e de invocação especificados.The method that is to be invoked must be accessible and provide the most specific match with the specified argument list, under the constraints of the specified binder and invocation attributes.

Um método será invocado se o número de parâmetros na declaração do método for igual ao número de argumentos na lista de argumentos especificada e o tipo de cada argumento puder ser convertido pelo associador para o tipo do parâmetro.A method is invoked if the number of parameters in the method declaration equals the number of arguments in the specified argument list, and the type of each argument can be converted by the binder to the type of the parameter.

Observação

A matriz de modificadores de parâmetro passados para o InvokeMember método deve conter um único modificador de parâmetro.The array of parameter modifiers passed to the InvokeMember method must contain a single parameter modifier. Somente o primeiro modificador de parâmetro é considerado ao determinar qual argumento precisa ser passado por referência quando exposto a COM.Only the first parameter modifier is considered when determining which argument needs to be passed by reference when exposed to COM.

O associador localiza todos os métodos correspondentes, de acordo com o tipo de associação solicitada ( BindingFlags.InvokeMethod , GetProperties e assim por diante).The binder finds all matching methods, in accordance with the type of binding requested (BindingFlags.InvokeMethod, GetProperties, and so on). O conjunto de métodos é filtrado pelo nome, número de argumentos e um conjunto de modificadores de pesquisa definidos no associador.The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder. Depois que o método é selecionado, ele é invocado e a acessibilidade é verificada nesse ponto.After the method is selected, it is invoked, and accessibility is checked at that point. A pesquisa pode controlar qual conjunto de métodos é pesquisado com base no atributo de acessibilidade associado ao método.The search may control which set of methods is searched based upon the accessibility attribute associated with the method. BindToMethod seleciona o método a ser invocado.BindToMethod selects the method to be invoked. O associador padrão seleciona a correspondência mais específica.The default binder selects the most specific match.

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 through reflection whenever the code is fully trusted.

Aplica-se a

Confira também