Type.GetMethod Método

Definição

Obtém um método específico da corrente Type.

Sobrecargas

Name Description
GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Procura o método especificado cujos parâmetros correspondem à contagem genérica de parâmetros especificada, tipos de argumentos e modificadores, usando as restrições de ligação especificadas e a convenção de chamada especificada.

GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Procura o método especificado cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de ligação especificadas e a convenção de chamada especificada.

GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[])

Procura o método especificado cujos parâmetros correspondem à contagem genérica de parâmetros especificada, tipos de argumentos e modificadores, usando as restrições de ligação especificadas.

GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Procura o método especificado cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de ligação especificadas.

GetMethod(String, Int32, Type[], ParameterModifier[])

Pesquisa pelo método público especificado cujos parâmetros correspondem à contagem genérica de parâmetros, tipos de argumentos e modificadores especificados.

GetMethod(String, Int32, BindingFlags, Type[])

Procura o método especificado cujos parâmetros correspondem à contagem genérica de parâmetros e aos tipos de argumentos especificados, usando as restrições de ligação especificadas.

GetMethod(String, Int32, Type[])

Pesquisa pelo método público especificado cujos parâmetros correspondem à contagem genérica de parâmetros e aos tipos de argumentos especificados.

GetMethod(String, BindingFlags, Type[])

Procura o método especificado cujos parâmetros correspondem aos tipos de argumentos especificados, usando as restrições de ligação especificadas.

GetMethod(String, Type[])

Pesquisa pelo método público especificado cujos parâmetros correspondem aos tipos de argumento especificados.

GetMethod(String, BindingFlags)

Procura o método especificado, usando as restrições de ligação especificadas.

GetMethod(String)

Pesquisas pelo método público com o nome especificado.

GetMethod(String, Type[], ParameterModifier[])

Procura o método público especificado cujos parâmetros correspondem aos tipos de argumentos e modificadores especificados.

GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado cujos parâmetros correspondem à contagem genérica de parâmetros especificada, tipos de argumentos e modificadores, usando as restrições de ligação especificadas e a convenção de chamada especificada.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * int * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
member this.GetMethod : string * int * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, genericParameterCount As Integer, bindingAttr As BindingFlags, binder As Binder, callConvention As CallingConventions, types As Type(), modifiers As ParameterModifier()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

genericParameterCount
Int32

O número de parâmetros genéricos de tipo do método.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.

-ou-

Default para regressar null.

binder
Binder

Um objeto que define um conjunto de propriedades e permite a ligação, que pode envolver a seleção de um método sobrecarregado, a coerção dos tipos de argumentos e a invocação de um membro através da reflexão.

-ou-

Uma referência nula (Nothing em Visual Basic), para usar o DefaultBinder.

callConvention
CallingConventions

O objeto que especifica o conjunto de regras a usar relativamente à ordem e disposição dos argumentos, como o valor de retorno é passado, que registos são usados para argumentos e como a pilha é limpa.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

modifiers
ParameterModifier[]

Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. Para ser usado apenas ao chamar através da interoperação COM, e apenas os parâmetros que são passados por referência são tratados. O binder padrão não processa este parâmetro.

Devoluções

Um objeto que representa o método que corresponde à contagem genérica de parâmetros especificada, tipos de argumentos, modificadores, restrições de ligação e convenção de chamada, se encontrado; caso contrário, null.

Atributos

Exceções

name é null.

-ou-

types é null.

-ou-

Um dos elementos do types array é null.

genericParameterCount é negativo.

Aplica-se a

GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de ligação especificadas e a convenção de chamada especificada.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.MethodInfo GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
member this.GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
abstract member GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
override this.GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, bindingAttr As BindingFlags, binder As Binder, callConvention As CallingConventions, types As Type(), modifiers As ParameterModifier()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método a obter.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.

-ou-

Default para regressar null.

binder
Binder

Um objeto que define um conjunto de propriedades e permite a ligação, que pode envolver a seleção de um método sobrecarregado, a coerção dos tipos de argumentos e a invocação de um membro através da reflexão.

-ou-

Uma referência nula (Nothing em Visual Basic), para usar o DefaultBinder.

callConvention
CallingConventions

O objeto que especifica o conjunto de regras a usar relativamente à ordem e disposição dos argumentos, como o valor de retorno é passado, que registos são usados para argumentos e como a pilha é limpa.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

modifiers
ParameterModifier[]

Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. Para ser usado apenas ao chamar através da interoperação COM, e apenas os parâmetros que são passados por referência são tratados. O binder padrão não processa este parâmetro.

Devoluções

Um objeto que representa o método que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.

Implementações

Atributos

Exceções

Mais do que um método é encontrado com o nome especificado e correspondendo às restrições de ligação especificadas.

name é null.

-ou-

types é null.

-ou-

Um dos elementos em types é null.

types é multidimensional.

-ou-

modifiers é multidimensional.

Exemplos

O exemplo seguinte encontra sobrecargas específicas de MethodA, especificando restrições de ligação, chamadas de convenções e uma variedade de tipos de argumentos.

Note

O exemplo do Visual C# 2005 requer a /unsafe opção do compilador.


using System;
using System.Reflection;

class Program3
{
    // Methods to get:

    public void MethodA(int i, int j) { }

    public void MethodA(int[] i) { }

    public unsafe void MethodA(int* i) { }

    public void MethodA(ref int r) {}

    // Method that takes an out parameter:
    public void MethodA(int i, out int o) { o = 100;}

  static void Main(string[] args)
  {
    MethodInfo mInfo;

    // Get MethodA(int i, int j)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int), typeof(int) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int[] i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int[]) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int* i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int).MakePointerType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(ref int r)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int i, out int o)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int), typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);
  }
}
open System.Reflection

type Program() =
    // Methods to get:
    member _.MethodA(i: int, j: int) = ()

    member _.MethodA(i: int[]) = ()
    
    member _.MethodA(i: int nativeptr) = ()

    member _.MethodA(r: int byref) = ()

    // Method that takes an outref parameter:
    member _.MethodA(i: int, o: int outref) = o <- 100

do
    // Get MethodA(int i, int j)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA", BindingFlags.Public ||| BindingFlags.Instance, null, CallingConventions.Any, [| typeof<int>; typeof<int> |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(int[] i)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA", BindingFlags.Public ||| BindingFlags.Instance, null, CallingConventions.Any, [| typeof<int[]> |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(int* i)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA", BindingFlags.Public ||| BindingFlags.Instance, null, CallingConventions.Any, [| typeof<int>.MakePointerType() |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(ref int r)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA", BindingFlags.Public ||| BindingFlags.Instance, null, CallingConventions.Any, [| typeof<int>.MakeByRefType() |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(int i, out int o)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA", BindingFlags.Public ||| BindingFlags.Instance, null, CallingConventions.Any, [| typeof<int>; typeof<int>.MakeByRefType() |], null)
    printfn $"Found method: {mInfo}"

Imports System.Reflection
Imports System.Runtime.InteropServices

Class Program

    ' Methods to get:
    
    Public Overloads Sub MethodA(ByVal i As Integer, ByVal l As Long)

    End Sub

    Public Overloads Sub MethodA(ByVal i() As Integer)

    End Sub

    Public Overloads Sub MethodA(ByRef r As Integer)

    End Sub

    ' Method that takes an integer and an out parameter. Note that an
    ' Imports reference is needed to System.Runtime.InteropServices
    ' for the <OutAttribute>, which can be shortened to <Out>.
    Public Overloads Sub MethodA(ByVal i As Integer, <Out()> ByRef o As Integer)
        o = 100
    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim mInfo As MethodInfo

        ' Get MethodA(ByVal i As Integer, ByVal l As Long)
        mInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance, _
            Nothing, _
            CallingConventions.Any, _
            New Type() {GetType(System.Int32), _
            GetType(System.Int64)}, _
            Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get  MethodA(ByVal i() As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance, _
            Nothing, _
            CallingConventions.Any, _
            New Type() {GetType(System.Int32())}, _
            Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(ByRef r As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", _
        BindingFlags.Public Or BindingFlags.Instance, _
        Nothing, _
        CallingConventions.Any, _
        New Type() {GetType(System.Int32).MakeByRefType}, _
        Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(ByVal i As Integer, <Out()> ByRef o As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", _
        BindingFlags.Public Or BindingFlags.Instance, _
        Nothing, _
        CallingConventions.Any, _
        New Type() {GetType(System.Int32), GetType(System.Int32).MakeByRefType}, _
        Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

    End Sub
End Class

Observações

Embora o fichário padrão não processe ParameterModifier (o modifiers parâmetro), você pode usar a classe abstrata System.Reflection.Binder para escrever um fichário personalizado que processa modifiers. ParameterModifier é utilizado apenas ao fazer chamadas através da interoperabilidade COM, e apenas os parâmetros que são passados por referência são tratados.

A tabela a seguir mostra quais membros de uma classe base são retornados pelos GetXXX métodos ao refletir sobre um tipo.

Tipo de Membro Estático Não-estático
Construtor No No
Campo No Yes. Um campo é sempre ocultado com base no nome e assinatura.
Evento Não aplicável A regra comum do sistema de tipos é que a herança é a mesma dos métodos que implementam a propriedade. A reflexão trata propriedades como esconder pelo nome e assinatura. Veja a nota 2 abaixo.
Método No Yes. Um método (virtual e não virtual) pode ser ocultado por nome ou ocultado por nome e assinatura.
Tipo aninhado No No
Property Não aplicável A regra comum do sistema de tipos é que a herança é a mesma dos métodos que implementam a propriedade. A reflexão trata propriedades como esconder pelo nome e assinatura. Veja a nota 2 abaixo.
  1. Ocultar por nome e assinatura considera todas as partes da assinatura, incluindo modificadores personalizados, tipos de retorno, tipos de parâmetros, sentinelas e convenções de chamada não gerenciadas. Esta é uma comparação binária.

  2. Para reflexão, as propriedades e os eventos são ocultados por nome e assinatura. Se você tiver uma propriedade com um acessador get e um set na classe base, mas a classe derivada tiver apenas um acessor get, a propriedade de classe derivada ocultará a propriedade de classe base e você não poderá acessar o setter na classe base.

  3. Os atributos personalizados não fazem parte do sistema de tipo comum.

As seguintes BindingFlags bandeiras de filtro podem ser usadas para definir quais os métodos a incluir na pesquisa:

  • Você deve especificar ou BindingFlags.Instance ou BindingFlags.Static para obter um retorno.

  • Especifique BindingFlags.Public incluir métodos públicos na pesquisa.

  • Especifique BindingFlags.NonPublic incluir métodos não públicos (ou seja, privados, internos e protegidos) na pesquisa.

  • Especifique BindingFlags.FlattenHierarchy para incluir public e protected membros estáticos na hierarquia; private membros estáticos em classes herdadas não são incluídos.

Os seguintes BindingFlags sinalizadores modificadores podem ser usados para alterar o funcionamento da pesquisa:

  • BindingFlags.IgnoreCase ignorar o caso de name.

  • BindingFlags.DeclaredOnly pesquisar apenas os métodos declarados no Type, não os métodos que foram simplesmente herdados.

Consulte System.Reflection.BindingFlags para obter mais informações.

Note

Não podes omitir parâmetros ao procurar construtores e métodos. Só podes omitir parâmetros ao invocar.

Se o current Type representa um tipo genérico construído, esse método retorna o MethodInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.

Se a corrente Type representa um parâmetro de tipo na definição de um tipo genérico ou método genérico, este método pesquisa os métodos da restrição de classe, ou os métodos de Object se não houver restrição de classe.

Note

Para métodos genéricos, não inclua os argumentos tipo em name. Por exemplo, o código GetMember("MyMethod<int>") C# procura um membro com o nome de texto "MyMethod<int>", em vez de um método nomeado MyMethod que tenha um argumento genérico do tipo int.

Ver também

Aplica-se a

GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado cujos parâmetros correspondem à contagem genérica de parâmetros especificada, tipos de argumentos e modificadores, usando as restrições de ligação especificadas.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * int * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
member this.GetMethod : string * int * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, genericParameterCount As Integer, bindingAttr As BindingFlags, binder As Binder, types As Type(), modifiers As ParameterModifier()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

genericParameterCount
Int32

O número de parâmetros genéricos de tipo do método.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.

-ou-

Default para regressar null.

binder
Binder

Um objeto que define um conjunto de propriedades e permite a ligação, que pode envolver a seleção de um método sobrecarregado, a coerção dos tipos de argumentos e a invocação de um membro através da reflexão.

-ou-

Uma referência nula (Nothing em Visual Basic), para usar o DefaultBinder.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

modifiers
ParameterModifier[]

Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. Para ser usado apenas ao chamar através da interoperação COM, e apenas os parâmetros que são passados por referência são tratados. O binder padrão não processa este parâmetro.

Devoluções

Um objeto que representa o método que corresponde à contagem genérica de parâmetros especificada, tipos de argumentos, modificadores e restrições de ligação, se encontrado; caso contrário, null.

Atributos

Exceções

name é null.

-ou-

types é null.

-ou-

Um dos elementos do types array é null.

genericParameterCount é negativo.

Aplica-se a

GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de ligação especificadas.

public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.MethodInfo GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
abstract member GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
override this.GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
abstract member GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
override this.GetMethod : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, bindingAttr As BindingFlags, binder As Binder, types As Type(), modifiers As ParameterModifier()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método a obter.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.

-ou-

Default para regressar null.

binder
Binder

Um objeto que define um conjunto de propriedades e permite a ligação, que pode envolver a seleção de um método sobrecarregado, a coerção dos tipos de argumentos e a invocação de um membro através da reflexão.

-ou-

Uma referência nula (Nothing em Visual Basic), para usar o DefaultBinder.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

modifiers
ParameterModifier[]

Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. Para ser usado apenas ao chamar através da interoperação COM, e apenas os parâmetros que são passados por referência são tratados. O binder padrão não processa este parâmetro.

Devoluções

Um objeto que representa o método que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.

Implementações

Atributos

Exceções

Mais do que um método é encontrado com o nome especificado e correspondendo às restrições de ligação especificadas.

name é null.

-ou-

types é null.

-ou-

Um dos elementos em types é null.

types é multidimensional.

-ou-

modifiers é multidimensional.

Exemplos

O exemplo seguinte encontra sobrecargas específicas de MethodA, especificando restrições de ligação e uma variedade de tipos de argumentos.

Note

O exemplo do Visual C# 2005 requer a /unsafe opção do compilador.


using System;
using System.Reflection;

class Program5
{
    // Methods to get:

    public void MethodA(int i, int j) { }

    public void MethodA(int[] i) { }

    public unsafe void MethodA(int* i) { }

    public void MethodA(ref int r) {}

    // Method that takes an out parameter.
    public void MethodA(int i, out int o) { o = 100; }

  static void Main(string[] args)
  {
    MethodInfo mInfo;

    // Get MethodA(int i, int j)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int), typeof(int) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int[] i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int[]) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int* i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int).MakePointerType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(ref int r)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int i, out int o)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int), typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);
  }
}
open System
open System.Reflection

type Program() =
    // Methods to get:
    member _.MethodA(i: int, j: int) = ()

    member _.MethodA(i: int[]) = ()
    
    member _.MethodA(i: int nativeptr) = ()

    member _.MethodA(r: int byref) = ()

    // Method that takes an outref parameter:
    member _.MethodA(i: int, o: int outref) = o <- 100

do
    // Get MethodA(int i, int j)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA",BindingFlags.Public ||| BindingFlags.Instance, null, [| typeof<int>; typeof<int> |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(int[] i)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA",BindingFlags.Public ||| BindingFlags.Instance, null, [| typeof<int[]> |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(int* i)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA",BindingFlags.Public ||| BindingFlags.Instance, null, [| typeof<int>.MakePointerType() |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(ref int r)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA",BindingFlags.Public ||| BindingFlags.Instance, null, [| typeof<int>.MakeByRefType() |], null)
    printfn $"Found method: {mInfo}"

    // Get MethodA(int i, out int o)
    let mInfo = 
        typeof<Program>.GetMethod("MethodA",BindingFlags.Public ||| BindingFlags.Instance, null, [| typeof<int>; typeof<int>.MakeByRefType() |], null)
    printfn $"Found method: {mInfo}"

Imports System.Reflection
Imports System.Runtime.InteropServices

Class Program

    ' Methods to get:
    
    Public Overloads Sub MethodA(ByVal i As Integer, ByVal l As Long)

    End Sub

    Public Overloads Sub MethodA(ByVal i() As Integer)

    End Sub

    Public Overloads Sub MethodA(ByRef r As Integer)

    End Sub

    ' Method that takes an out parameter. Note that an Imports
    ' reference is needed to System.Runtime.InteropServices 
    ' for the <OutAttribute>, which can be shortened to <Out>.
    Public Overloads Sub MethodA(ByVal i As Integer, <Out()> ByRef o As Integer)
        o = 100
    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim mInfo As MethodInfo

        ' Get MethodA(ByVal i As Integer, ByVal l As Long)
        mInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance, _
            Nothing, _
            New Type() {GetType(System.Int32), _
            GetType(System.Int64)}, _
            Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(ByVal i() As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance, _
            Nothing, _
            New Type() {GetType(System.Int32())}, _
            Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(ByRef r As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance, _
            Nothing, _
            New Type() {GetType(System.Int32).MakeByRefType}, _
            Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(ByVal i As Integer, <Out()> ByRef o As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance, _
            Nothing, _
            New Type() {GetType(System.Int32), GetType(System.Int32).MakeByRefType}, _
            Nothing)
        Console.WriteLine("Found method: {0}", mInfo)

    End Sub
End Class

Observações

Embora o fichário padrão não processe ParameterModifier (o modifiers parâmetro), você pode usar a classe abstrata System.Reflection.Binder para escrever um fichário personalizado que processa modifiers. ParameterModifier é utilizado apenas ao fazer chamadas através da interoperabilidade COM, e apenas os parâmetros que são passados por referência são tratados.

As seguintes BindingFlags bandeiras de filtro podem ser usadas para definir quais os métodos a incluir na pesquisa:

  • Você deve especificar ou BindingFlags.Instance ou BindingFlags.Static para obter um retorno.

  • Especifique BindingFlags.Public incluir métodos públicos na pesquisa.

  • Especifique BindingFlags.NonPublic incluir métodos não públicos (ou seja, privados, internos e protegidos) na pesquisa.

  • Especifique BindingFlags.FlattenHierarchy para incluir public e protected membros estáticos na hierarquia; private membros estáticos em classes herdadas não são incluídos.

Os seguintes BindingFlags sinalizadores modificadores podem ser usados para alterar o funcionamento da pesquisa:

  • BindingFlags.IgnoreCase ignorar o caso de name.

  • BindingFlags.DeclaredOnly pesquisar apenas os métodos declarados no Type, não os métodos que foram simplesmente herdados.

Consulte System.Reflection.BindingFlags para obter mais informações.

Note

Não podes omitir parâmetros ao procurar construtores e métodos. Só podes omitir parâmetros ao invocar.

Se o current Type representa um tipo genérico construído, esse método retorna o MethodInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.

Se a corrente Type representa um parâmetro de tipo na definição de um tipo genérico ou método genérico, este método pesquisa os métodos da restrição de classe, ou os métodos de Object se não houver restrição de classe.

Note

Para métodos genéricos, não inclua os argumentos tipo em name. Por exemplo, o código GetMember("MyMethod<int>") C# procura um membro com o nome de texto "MyMethod<int>", em vez de um método nomeado MyMethod que tenha um argumento genérico do tipo int.

Ver também

Aplica-se a

GetMethod(String, Int32, Type[], ParameterModifier[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa pelo método público especificado cujos parâmetros correspondem à contagem genérica de parâmetros, tipos de argumentos e modificadores especificados.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * int * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
member this.GetMethod : string * int * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, genericParameterCount As Integer, types As Type(), modifiers As ParameterModifier()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

genericParameterCount
Int32

O número de parâmetros genéricos de tipo do método.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

modifiers
ParameterModifier[]

Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. Para ser usado apenas ao chamar através da interoperação COM, e apenas os parâmetros que são passados por referência são tratados. O binder padrão não processa este parâmetro.

Devoluções

Um objeto que representa o método público que corresponde à contagem genérica de parâmetros especificada, tipos de argumentos e modificadores, se encontrado; caso contrário, null.

Atributos

Exceções

name é null.

-ou-

types é null.

-ou-

Um dos elementos do types array é null.

genericParameterCount é negativo.

Aplica-se a

GetMethod(String, Int32, BindingFlags, Type[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado cujos parâmetros correspondem à contagem genérica de parâmetros e aos tipos de argumentos especificados, usando as restrições de ligação especificadas.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * int * System.Reflection.BindingFlags * Type[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, genericParameterCount As Integer, bindingAttr As BindingFlags, types As Type()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método a obter.

genericParameterCount
Int32

O número de parâmetros genéricos de tipo do método.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.

-ou-

Default para regressar null.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

Devoluções

Um objeto que representa o método que corresponde à contagem genérica de parâmetros especificada, tipos de argumentos e restrições de ligação, se encontrada; caso contrário, null.

Atributos

Aplica-se a

GetMethod(String, Int32, Type[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa pelo método público especificado cujos parâmetros correspondem à contagem genérica de parâmetros e aos tipos de argumentos especificados.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, cli::array <Type ^> ^ types);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types);
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, Type[] types);
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * int * Type[] -> System.Reflection.MethodInfo
member this.GetMethod : string * int * Type[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, genericParameterCount As Integer, types As Type()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

genericParameterCount
Int32

O número de parâmetros genéricos de tipo do método.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

Devoluções

Um objeto que representa o método público cujos parâmetros correspondem à contagem genérica de parâmetros e aos tipos de argumentos especificados, se encontrados; caso contrário, null.

Atributos

Exceções

name é null.

-ou-

types é null.

-ou-

Um dos elementos do types array é null.

genericParameterCount é negativo.

Aplica-se a

GetMethod(String, BindingFlags, Type[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado cujos parâmetros correspondem aos tipos de argumentos especificados, usando as restrições de ligação especificadas.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * System.Reflection.BindingFlags * Type[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, bindingAttr As BindingFlags, types As Type()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método a obter.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada. -ou- Por defeito para retornar null.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter. -ou- Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

Devoluções

Um objeto que representa o método que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.

Atributos

Aplica-se a

GetMethod(String, Type[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa pelo método público especificado cujos parâmetros correspondem aos tipos de argumento especificados.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, cli::array <Type ^> ^ types);
public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, cli::array <Type ^> ^ types);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, Type[] types);
public System.Reflection.MethodInfo GetMethod(string name, Type[] types);
public System.Reflection.MethodInfo? GetMethod(string name, Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * Type[] -> System.Reflection.MethodInfo
member this.GetMethod : string * Type[] -> System.Reflection.MethodInfo
abstract member GetMethod : string * Type[] -> System.Reflection.MethodInfo
override this.GetMethod : string * Type[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, types As Type()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

Devoluções

Um objeto que representa o método público cujos parâmetros correspondem aos tipos de argumento especificados, se encontrados; caso contrário, null.

Implementações

Atributos

Exceções

Encontra-se mais do que um método com o nome e parâmetros especificados.

name é null.

-ou-

types é null.

-ou-

Um dos elementos em types é null.

types é multidimensional.

Exemplos

O exemplo seguinte encontra sobrecargas específicas de MethodA, especificando uma variedade de tipos de argumentos.

Note

O exemplo do Visual C# 2005 requer a /unsafe opção do compilador.


using System;
using System.Reflection;

class Program4
{
    // Methods to get:

    public void MethodA(int i, int j) { }

    public void MethodA(int[] i) { }

    public unsafe void MethodA(int* i) { }

    public void MethodA(ref int r) {}

    // Method that takes an out parameter:
    public void MethodA(int i, out int o) { o = 100;}

  static void Main(string[] args)
  {
    MethodInfo mInfo;

    // Get MethodA(int i, int i)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int), typeof(int) });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int[] i)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int[]) });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int* i)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int).MakePointerType() });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(ref int r)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int).MakeByRefType() });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int i, out int o)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int), typeof(int).MakeByRefType() });
    Console.WriteLine("Found method: {0}", mInfo);
  }
}
type Program() =
    // Methods to get:
    member _.MethodA(i: int, j: int) = ()

    member _.MethodA(i: int[]) = ()
    
    member _.MethodA(i: int nativeptr) = ()

    member _.MethodA(r: int byref) = ()

    // Method that takes an outref parameter:
    member _.MethodA(i: int, o: int outref) = o <- 100

do
    // member MethodA: i: int * j: int -> unit
    let mInfo = typeof<Program>.GetMethod("MethodA", [| typeof<int>; typeof<int> |])
    printfn $"Found method: {mInfo}"

    // member MethodA: i: int[] -> unit
    let mInfo = typeof<Program>.GetMethod("MethodA", [| typeof<int[]> |])
    printfn $"Found method: {mInfo}"

    // member MethodA: i: nativeptr<int> -> unit
    let mInfo = typeof<Program>.GetMethod("MethodA", [| typeof<int>.MakePointerType() |])
    printfn $"Found method: {mInfo}"

    // member MethodA: r: byref<int> -> unit
    let mInfo = typeof<Program>.GetMethod("MethodA", [| typeof<int>.MakeByRefType() |])
    printfn $"Found method: {mInfo}"

    // member MethodA: i: int * o: outref<int> -> unit
    let mInfo = typeof<Program>.GetMethod("MethodA", [| typeof<int>; typeof<int>.MakeByRefType() |])
    printfn $"Found method: {mInfo}"

Imports System.Reflection
Imports System.Runtime.InteropServices

Class Program

    ' Methods to get:

    Public Overloads Sub MethodA(ByVal i As Integer, ByVal l As Long)

    End Sub

    Public Overloads Sub MethodA(ByVal i() As Integer)

    End Sub

    Public Overloads Sub MethodA(ByRef r As Integer)

    End Sub

    ' Method that takes an out parameter. Note that an Imports
    ' reference is needed to System.Runtime.InteropServices 
    ' for the <OutAttribute>, which can be shortened to <Out>.
    Public Overloads Sub MethodA(ByVal i As Integer, <Out()> ByRef o As Integer)
        o = 100
    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim mInfo As MethodInfo

        ' Get MethodA(i As Integer i, l As Long)
        mInfo = GetType(Program).GetMethod("MethodA", New Type() {GetType(Integer), GetType(Long)})
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get  MethodA(i As Integer())
        mInfo = GetType(Program).GetMethod("MethodA", New Type() {GetType(Integer())})
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(ByRef r As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", New Type() {GetType(Integer).MakeByRefType})
        Console.WriteLine("Found method: {0}", mInfo)

        ' Get MethodA(i As Integer, ByRef r As Integer)
        mInfo = GetType(Program).GetMethod("MethodA", New Type() {GetType(Integer), _
            GetType(Integer).MakeByRefType})
        Console.WriteLine("Found method: {0}", mInfo)

    End Sub
End Class

O exemplo seguinte recupera MethodInfo objetos que representam os Add métodos de um tipo não genérico (a ArrayList classe), um tipo genérico aberto (a List<T> classe) e um tipo genérico fechado (o List(Of String) tipo.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      // Get a Type object that represents a non-generic type.
      GetAddMethod(typeof(ArrayList));

      var list = new List<String>();
      // Get a Type object that represents a constructed generic type.
      Type closed = list.GetType();
      GetAddMethod(closed);
      
      // Get a Type object that represents an open generic type.
      Type open = typeof(List<>);
      GetAddMethod(open);
   }

   private static void GetAddMethod(Type typ)
   {
      MethodInfo method;
      // Determine if this is a generic type.
      if (typ.IsGenericType) {
         // Is it an open generic type?
         if (typ.ContainsGenericParameters)
            method = typ.GetMethod("Add", typ.GetGenericArguments());
         // Get closed generic type arguments.
         else
            method = typ.GetMethod("Add", typ.GenericTypeArguments);
      }
      // This is not a generic type.
      else {
         method = typ.GetMethod("Add", new Type[] { typeof(Object) } );
      }

      // Test if an Add method was found.
      if (method == null) { 
         Console.WriteLine("No Add method found.");
         return;
      }   
      
      Type t = method.ReflectedType;
      Console.Write("{0}.{1}.{2}(", t.Namespace, t.Name, method.Name);
      ParameterInfo[] parms = method.GetParameters();
      for (int ctr = 0; ctr < parms.Length; ctr++)
         Console.Write("{0}{1}", parms[ctr].ParameterType.Name, 
                       ctr < parms.Length - 1 ? ", " : "");

      Console.WriteLine(")");
   }   
}
// The example displays the following output:
//       System.Collections.ArrayList.Add(Object)
//       System.Collections.Generic.List`1.Add(String)
//       System.Collections.Generic.List`1.Add(T)
open System
open System.Collections

let getAddMethod (typ: Type) = 
    let method = 
        // Determine if this is a generic type.
        if typ.IsGenericType then
            // Is it an open generic type?
            if typ.ContainsGenericParameters then
                typ.GetMethod("Add", typ.GetGenericArguments())
            // Get closed generic type arguments.
            else
                typ.GetMethod("Add", typ.GenericTypeArguments)
        // This is not a generic type.
        else
            typ.GetMethod("Add", [| typeof<obj> |])

    // Test if an Add method was found.
    if method = null then
        printfn "No Add method found."
    else
        let t = method.ReflectedType
        printf $"{t.Namespace}.{t.Name}.{method.Name}("
        let parms = method.GetParameters()
        for i = 0 to parms.Length - 1 do
            printf $"""{parms[i].ParameterType.Name}{if i < parms.Length - 1 then ", " else ""}"""
        printfn ")"

// Get a Type object that represents a non-generic type.
getAddMethod typeof<ArrayList>

let list = ResizeArray<String>()
// Get a Type object that represents a constructed generic type.
let closed = list.GetType()
getAddMethod closed

// Get a Type object that represents an open generic type.
let opn = typeof<ResizeArray<_>>.GetGenericTypeDefinition()
getAddMethod opn

// The example displays the following output:
//       System.Collections.ArrayList.Add(Object)
//       System.Collections.Generic.List`1.Add(String)
//       System.Collections.Generic.List`1.Add(T)
Imports System.Collections
Imports System.Collections.Generic
Imports System.Reflection

Module Example
   Public Sub Main()
      ' Get a Type object that represents a non-generic type.
      GetAddMethod(GetType(ArrayList))
      
      Dim list As New List(Of String)()
      ' Get a Type object that represents a constructed generic type.
      Dim closed As Type = list.GetType()
      GetAddMethod(closed)
      
      ' Get a Type object that represents an open generic type.
      Dim open As Type = GetType(List(Of))
      GetAddMethod(open)
   End Sub
   
   Private Sub GetAddMethod(typ As Type)
      Dim method As MethodInfo
      ' Determine if this is a generic type.
      If typ.IsGenericType Then
         ' Is it an open generic type?
         If typ.ContainsGenericParameters Then
            method = typ.GetMethod("Add", typ.GetGenericArguments())
         ' Get closed generic type arguments.
         Else
            method = typ.GetMethod("Add", typ.GenericTypeArguments)
         End If
      ' This is not a generic type.
      Else
         method = typ.GetMethod("Add", { GetType(Object) } )
      End If
      ' Test if an Add method was found.
      If method Is Nothing Then 
         Console.WriteLine("No Add method found.")
         Exit Sub
      End If   

      Dim t As Type = method.ReflectedType
      Console.Write("{0}.{1}.{2}(", t.Namespace, t.Name, method.Name)
      Dim params() As ParameterInfo = method.GetParameters()
      For ctr As Integer = 0 To params.Length - 1
         Console.Write("{0}{1}", params(ctr).ParameterType.Name, 
                       If(ctr < params.Length - 1, ", ", ""))
      Next
      Console.WriteLine(")")
   End Sub
End Module
' The example displays the following output:
'       System.Collections.ArrayList.Add(Object)
'       System.Collections.Generic.List`1.Add(String)
'       System.Collections.Generic.List`1.Add(T)

O exemplo define um GetAddMethod método que recupera o objeto apropriado MethodInfo . Para fornecer o types argumento a favor de um tipo genérico aberto, chama o Type.GetGenericArguments método. Para fornecer o types argumento para um tipo genérico fechado, recupera o valor da Type.GenericTypeArguments propriedade.

Observações

A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui métodos públicos estáticos e de instância pública.

Note

Não podes omitir parâmetros ao procurar construtores e métodos. Só podes omitir parâmetros ao invocar.

Se o current Type representa um tipo genérico construído, esse método retorna o MethodInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.

Se a corrente Type representa um parâmetro de tipo na definição de um tipo genérico ou método genérico, este método pesquisa os métodos da restrição de classe, ou os métodos de Object se não houver restrição de classe.

Note

O name parâmetro não pode incluir argumentos de tipo. Por exemplo, o código GetMethod("MyGenericMethod<int>") C# procura um método com o nome de texto "MyGenericMethod<int>", em vez de um método nomeado MyGenericMethod que tem um argumento genérico do tipo int. Em vez disso, use GetMethod("MyGenericMethod") com o parâmetro apropriado no types array.

Ver também

Aplica-se a

GetMethod(String, BindingFlags)

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método especificado, usando as restrições de ligação especificadas.

public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr);
public System.Reflection.MethodInfo GetMethod(string name, System.Reflection.BindingFlags bindingAttr);
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicMethods | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
abstract member GetMethod : string * System.Reflection.BindingFlags -> System.Reflection.MethodInfo
override this.GetMethod : string * System.Reflection.BindingFlags -> System.Reflection.MethodInfo
abstract member GetMethod : string * System.Reflection.BindingFlags -> System.Reflection.MethodInfo
override this.GetMethod : string * System.Reflection.BindingFlags -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, bindingAttr As BindingFlags) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método a obter.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.

-ou-

Default para regressar null.

Devoluções

Um objeto que representa o método que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.

Implementações

Atributos

Exceções

Mais do que um método é encontrado com o nome especificado e correspondendo às restrições de ligação especificadas.

name é null.

Exemplos

O exemplo seguinte obtém o método que corresponde aos flags de ligação especificados.

using System;
using System.Reflection;

class Program2
{
    // Method to get:
    public void MethodA() { }

    static void Main(string[] args)
    {
        // Get MethodA()
        MethodInfo mInfo = typeof(Program).GetMethod("MethodA",
            BindingFlags.Public | BindingFlags.Instance);
        Console.WriteLine("Found method: {0}", mInfo);
    }
}
open System.Reflection

type Program() =
    // Method to get:
    member _.MethodA() = ()

// Get MethodA()
let mInfo = typeof<Program>.GetMethod("MethodA", BindingFlags.Public ||| BindingFlags.Instance)
printfn $"Found method: {mInfo}"

Imports System.Reflection

Class Program

    ' Method to get:
    Public Sub MethodA()
    End Sub


    Public Shared Sub Main(ByVal args() As String)

        ' Get MethodA()
        Dim mInfo As MethodInfo = GetType(Program).GetMethod("MethodA", _
            BindingFlags.Public Or BindingFlags.Instance)
        Console.WriteLine("Found method: {0}", mInfo)

    End Sub
End Class

Observações

As seguintes BindingFlags bandeiras de filtro podem ser usadas para definir quais os métodos a incluir na pesquisa:

Os seguintes BindingFlags sinalizadores modificadores podem ser usados para alterar o funcionamento da pesquisa:

Consulte System.Reflection.BindingFlags para obter mais informações.

Se um método estiver sobrecarregado e mais do que uma sobrecarga cumprir as restrições especificadas pelo bindingAttr argumento, o método lança uma AmbiguousMatchException exceção. No exemplo seguinte, é lançada uma exceção porque:

  • O TestClass tipo tem duas sobrecargas públicas de instância do DisplayValue método, DisplayValue(String) e DisplayValue(String, Object[]).

  • O TestClass tipo tem duas sobrecargas públicas de instância do Equals método, uma das quais é herdada de Object: Equals(TestClass) e Equals(Object).

using System;
using System.Reflection;

public class TestClass
{
    public void DisplayValue(String s)
    {
        Console.WriteLine(s);
    }

    public void DisplayValue(String s, params Object[] values)
    {
        Console.WriteLine(s, values);
    }

    public static bool Equals(TestClass t1, TestClass t2)
    {
        return Object.ReferenceEquals(t1, t2);
    }

    public bool Equals(TestClass t)
    {
        return Object.ReferenceEquals(this, t);
    }
}

public class Example1
{
    public static void Main()
    {
        Type t = typeof(TestClass);

        RetrieveMethod(t, "DisplayValue", BindingFlags.Public | BindingFlags.Instance);

        RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Instance);

        RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

        RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Static);
    }

    private static void RetrieveMethod(Type t, String name, BindingFlags flags)
    {
        try
        {
            MethodInfo m = t.GetMethod(name, flags);
            if (m != null)
            {
                Console.Write("{0}.{1}(", t.Name, m.Name);
                ParameterInfo[] parms = m.GetParameters();
                for (int ctr = 0; ctr < parms.Length; ctr++)
                {
                    Console.Write(parms[ctr].ParameterType.Name);
                    if (ctr < parms.Length - 1)
                        Console.Write(", ");
                }
                Console.WriteLine(")");
            }
            else
            {
                Console.WriteLine("Method not found");
            }
        }
        catch (AmbiguousMatchException)
        {
            Console.WriteLine("The following duplicate matches were found:");
            MethodInfo[] methods = t.GetMethods(flags);
            foreach (var method in methods)
            {
                if (method.Name != name) continue;

                Console.Write("   {0}.{1}(", t.Name, method.Name);
                ParameterInfo[] parms = method.GetParameters();
                for (int ctr = 0; ctr < parms.Length; ctr++)
                {
                    Console.Write(parms[ctr].ParameterType.Name);
                    if (ctr < parms.Length - 1)
                        Console.Write(", ");
                }
                Console.WriteLine(")");
            }
        }
        Console.WriteLine();
    }
}
// The example displays the following output:
//       The following duplicate matches were found:
//          TestClass.DisplayValue(String)
//          TestClass.DisplayValue(String, Object[])
//       
//       The following duplicate matches were found:
//          TestClass.Equals(TestClass)
//          TestClass.Equals(Object)
//       
//       TestClass.Equals(TestClass)
//       
//       TestClass.Equals(TestClass, TestClass)
open System
open System.Reflection

type TestClass() =
    member _.DisplayValue(s) = 
        printfn $"%s{s}"

    member _.DisplayValue(s: string, [<ParamArray>]values: obj[]) =
        Console.WriteLine(s, values)

    member this.Equals(t: TestClass) =
        Object.ReferenceEquals(this, t)

    static member Equals(t1: TestClass, t2: TestClass) =
        Object.ReferenceEquals(t1, t2)

let retrieveMethod (t: Type) name (flags: BindingFlags) =
    try
        let m = t.GetMethod(name, flags)
        if m <> null then
            printf $"{t.Name}.{m.Name}("
            let parms = m.GetParameters()
            for i = 0 to parms.Length - 1 do
                printf $"{parms[i].ParameterType.Name}"
                if i < parms.Length - 1 then
                    printf ", "
            printfn ")"
        else
            printfn "Method not found"
    with :? AmbiguousMatchException ->
        printfn "The following duplicate matches were found:"
        let methods = t.GetMethods flags
        for method in methods do
            if method.Name = name then
                printf $"   {t.Name}.{method.Name}("
                let parms = method.GetParameters()
                for i = 0 to parms.Length - 1 do
                    printf $"{parms[i].ParameterType.Name}"
                    if i < parms.Length - 1 then
                        printf ", "
                printfn ")"
    printfn ""

let t = typeof<TestClass>

retrieveMethod t "DisplayValue" (BindingFlags.Public ||| BindingFlags.Instance)

retrieveMethod t "Equals" (BindingFlags.Public ||| BindingFlags.Instance)

retrieveMethod t "Equals" (BindingFlags.Public ||| BindingFlags.Instance ||| BindingFlags.DeclaredOnly)

retrieveMethod t "Equals" (BindingFlags.Public ||| BindingFlags.Static)

// The example displays the following output:
//       The following duplicate matches were found:
//          TestClass.DisplayValue(String)
//          TestClass.DisplayValue(String, Object[])
//       
//       The following duplicate matches were found:
//          TestClass.Equals(TestClass)
//          TestClass.Equals(Object)
//       
//       TestClass.Equals(TestClass)
//       
//       TestClass.Equals(TestClass, TestClass)
Imports System.Reflection

Public Class TestClass
   Public Sub DisplayValue(s As String)
      Console.WriteLine(s)
   End Sub
   
   Public Sub DisplayValue(s As String, ParamArray values() As Object)
      Console.WriteLine(s, values)
   End Sub
   
   Public Overloads Shared Function Equals(t1 As TestClass, t2 As TestClass) As Boolean
      Return Object.ReferenceEquals(t1, t2)
   End Function
   
   Public Overloads Function Equals(t As TestClass) As Boolean
      Return Object.ReferenceEquals(Me, t)
   End Function          
End Class

Module Example
   Public Sub Main()
      Dim t As Type = GetType(TestClass)
      
      RetrieveMethod(t, "DisplayValue", BindingFlags.Public Or BindingFlags.Instance)

      RetrieveMethod(t, "Equals", BindingFlags.Public Or BindingFlags.Instance)
      
      RetrieveMethod(t, "Equals", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)
      
      RetrieveMethod(t, "Equals", BindingFlags.Public Or BindingFlags.Static)
   End Sub
   
   Public Sub RetrieveMethod(t As Type, name As String, flags As BindingFlags)
      Try
         Dim m As MethodInfo = t.GetMethod(name, flags)
         If m IsNot Nothing Then
            Console.Write("{0}.{1}(", t.Name, m.Name)
           Dim parms() As ParameterInfo = m.GetParameters()
            For ctr As Integer = 0 To parms.Length - 1
               Console.Write(parms(ctr).ParameterType.Name)
               if ctr < parms.Length - 1 Then 
                  Console.Write(", ")
               End If      
            Next
            Console.WriteLine(")")
         Else
            Console.WriteLine("Method not found")
         End If
      Catch e As AmbiguousMatchException
         Console.WriteLine("The following duplicate matches were found:")
         Dim methods() As MethodInfo = t.GetMethods(flags)
         For Each method In methods
            If method.Name <> name Then Continue For

            Console.Write("   {0}.{1}(", t.Name, method.Name)
            Dim parms() As ParameterInfo = method.GetParameters()
            For ctr As Integer = 0 To parms.Length - 1
               Console.Write(parms(ctr).ParameterType.Name)
               if ctr < parms.Length - 1 Then 
                  Console.Write(", ")
               End If      
            Next
            Console.WriteLine(")")
         Next 
      End Try         
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'       The following duplicate matches were found:
'          TestClass.DisplayValue(String)
'          TestClass.DisplayValue(String, Object[])
'       
'       The following duplicate matches were found:
'          TestClass.Equals(TestClass)
'          TestClass.Equals(Object)
'       
'       TestClass.Equals(TestClass)
'       
'       TestClass.Equals(TestClass, TestClass)

Pode fazer uma das seguintes ações para obter um método específico:

  • Muda as restrições de ligação. No exemplo anterior, tentar recuperar um método de instância Equals pública que é declarado pelo tipo e não herdado recupera Equals(TestClass)com sucesso .

  • Chama-se uma sobrecarga do GetMethod método que inclui um types parâmetro que define os tipos dos parâmetros do método.

  • Chame o GetMethods(BindingFlags) método para recuperar um array que contenha todos os métodos pertencentes a um tipo que tenham os atributos de ligação especificados. Pode então iterar para identificar os métodos duplicados chamados name. Esta abordagem é ilustrada no handler do exemplo anterior para a AmbiguousMatchException exceção.

Se o current Type representa um tipo genérico construído, esse método retorna o MethodInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.

Se a corrente Type representa um parâmetro de tipo na definição de um tipo genérico ou método genérico, este método pesquisa os métodos da restrição de classe, ou os métodos de Object se não houver restrição de classe.

Note

Para métodos genéricos, não inclua os argumentos tipo em name. Por exemplo, o código GetMember("MyMethod<int>") C# procura um membro com o nome de texto "MyMethod<int>", em vez de um método nomeado MyMethod que tenha um argumento genérico do tipo int.

Ver também

Aplica-se a

GetMethod(String)

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisas pelo método público com o nome especificado.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name);
public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name);
public System.Reflection.MethodInfo GetMethod(string name);
public System.Reflection.MethodInfo? GetMethod(string name);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string -> System.Reflection.MethodInfo
member this.GetMethod : string -> System.Reflection.MethodInfo
abstract member GetMethod : string -> System.Reflection.MethodInfo
override this.GetMethod : string -> System.Reflection.MethodInfo
Public Function GetMethod (name As String) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

Devoluções

Um objeto que representa o método público com o nome especificado, se encontrado; caso contrário, null.

Implementações

Atributos

Exceções

Mais do que um método é encontrado com o nome especificado.

name é null.

Exemplos

O exemplo seguinte obtém um método chamado MethodA.


using System;
using System.Reflection;

class Program
{

    // Method to get:
    public void MethodA() { }

    static void Main(string[] args)
    {

        // Get MethodA()
        MethodInfo mInfo = typeof(Program).GetMethod("MethodA");
        Console.WriteLine("Found method: {0}", mInfo);
    }
}
type Program() =
    // Method to get:
    member _.MethodA() = ()

// Get MethodA()
let mInfo = typeof<Program>.GetMethod "MethodA"
printfn $"Found method: {mInfo}"

Imports System.Reflection

Class Program

    ' Method to get:
    Public Sub MethodA()
    End Sub


    Public Shared Sub Main(ByVal args() As String)

        ' Get MethodA()
        Dim mInfo As MethodInfo = GetType(Program).GetMethod("MethodA")
        Console.WriteLine("Found method: {0}", mInfo)

    End Sub
End Class

Observações

A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui métodos públicos estáticos e de instância pública.

Se um método estiver sobrecarregado e tiver mais do que um método público, o GetMethod(String) método lança uma AmbiguousMatchException exceção. No exemplo seguinte, é lançada uma exceção porque há mais do que uma sobrecarga pública do Int32.ToString método. Por outro lado, como o Person.ToString método sobrescreve Object.ToString e, portanto, não está sobrecarregado, o GetMethod(String) método consegue recuperar o MethodInfo objeto.

using System;
using System.Reflection;

public class Person
{
    public String FirstName;
    public String LastName;

    public override String ToString()
    {
        return (FirstName + " " + LastName).Trim();
    }
}

public class Example2
{
    public static void Main()
    {
        Type t = typeof(Person);
        RetrieveMethod(t, "ToString");

        t = typeof(Int32);
        RetrieveMethod(t, "ToString");
    }

    private static void RetrieveMethod(Type t, String name)
    {
        try
        {
            MethodInfo m = t.GetMethod(name);
            if (m != null)
                Console.WriteLine("{0}.{1}: {2} method", m.ReflectedType.Name,
                                  m.Name, m.IsStatic ? "Static" : "Instance");
            else
                Console.WriteLine("{0}.ToString method not found", t.Name);
        }
        catch (AmbiguousMatchException)
        {
            Console.WriteLine("{0}.{1} has multiple public overloads.",
                              t.Name, name);
        }
    }
}
// The example displays the following output:
//       Person.ToString: Instance method
//       Int32.ToString has multiple public overloads.
open System
open System.Reflection

type Person() =
    member val FirstName = "" with get, set
    member val LastName = "" with get, set

    override this.ToString() =
        (this.FirstName + " " + this.LastName).Trim()

let retrieveMethod (t: Type) name =
    try
        let m = t.GetMethod name
        if m <> null then
            printfn $"""{m.ReflectedType.Name}.{m.Name}: {if m.IsStatic then "Static" else "Instance"} method"""
        else
            printfn $"{t.Name}.ToString method not found"
    with :? AmbiguousMatchException ->
        printfn $"{t.Name}.{name} has multiple public overloads."

let t = typeof<Person>
retrieveMethod t "ToString"

let t2 = typeof<int>
retrieveMethod t2 "ToString"

// The example displays the following output:
//       Person.ToString: Instance method
//       Int32.ToString has multiple public overloads.
Imports System.Reflection

Public Class Person
   Public FirstName As String
   Public LastName As String
   
   Public Overrides Function ToString() As String
      Return (FirstName + " " + LastName).Trim()
   End Function
End Class

Module Example
   Public Sub Main()
      Dim t As Type = GetType(Person)
      RetrieveMethod(t, "ToString")
      
      t = GetType(Int32)
      RetrieveMethod(t, "ToString")
   End Sub
   
   Private Sub RetrieveMethod(t As Type, name As String)   
      Try
         Dim m As MethodInfo = t.GetMethod(name)
         If m IsNot Nothing Then
            Console.WriteLine("{0}.{1}: {2} method", m.ReflectedType.Name,
                              m.Name, If(m.IsStatic, "Static", "Instance"))    
         Else
            Console.WriteLine("{0}.ToString method not found", t.Name)
         End If   
      Catch e As AmbiguousMatchException
         Console.WriteLine("{0}.{1} has multiple public overloads.", 
                           t.Name, name)
      End Try
   End Sub
End Module
' The example displays the following output:
'       Person.ToString: Instance method
'       Int32.ToString has multiple public overloads.

Pode fazer uma das seguintes ações para obter um método específico:

  • Chame o GetMethod(String, BindingFlags) método e especifique um bindingAttr argumento que identifique de forma única o método. Por exemplo, se a exceção for lançada porque um tipo tem uma estática e uma sobrecarga de instância, pode-se especificar um bindingAttr argumento de BindingFlags.Static ou BindingFlags.Instance.

  • Chama-se uma sobrecarga do GetMethod método que inclui um types parâmetro que define os tipos dos parâmetros do método.

  • Chame o GetMethods() método para recuperar um array contendo todos os métodos públicos pertencentes a um tipo. Pode então iterar para identificar os métodos duplicados chamados name.

Se o current Type representa um tipo genérico construído, esse método retorna o MethodInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.

Se a corrente Type representa um parâmetro de tipo na definição de um tipo genérico ou método genérico, este método pesquisa os métodos da restrição de classe, ou os métodos de Object se não houver restrição de classe.

Note

Para métodos genéricos, não inclua os argumentos tipo em name. Por exemplo, o código GetMember("MyMethod<int>") C# procura um membro com o nome de texto "MyMethod<int>", em vez de um método nomeado MyMethod que tenha um argumento genérico do tipo int.

Ver também

Aplica-se a

GetMethod(String, Type[], ParameterModifier[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Procura o método público especificado cujos parâmetros correspondem aos tipos de argumentos e modificadores especificados.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]
public System.Reflection.MethodInfo? GetMethod(string name, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.MethodInfo GetMethod(string name, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.MethodInfo? GetMethod(string name, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)>]
member this.GetMethod : string * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
member this.GetMethod : string * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
abstract member GetMethod : string * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
override this.GetMethod : string * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, types As Type(), modifiers As ParameterModifier()) As MethodInfo

Parâmetros

name
String

A cadeia que contém o nome do método público a obter.

types
Type[]

Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para o método a obter.

-ou-

Um array vazio de Type objetos (conforme fornecido pelo EmptyTypes campo) para obter um método que não aceita parâmetros.

modifiers
ParameterModifier[]

Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. Para ser usado apenas ao chamar através da interoperação COM, e apenas os parâmetros que são passados por referência são tratados. O binder padrão não processa este parâmetro.

Devoluções

Um objeto que representa o método público que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.

Implementações

Atributos

Exceções

Encontra-se mais do que um método com o nome e parâmetros especificados.

name é null.

-ou-

types é null.

-ou-

Um dos elementos em types é null.

types é multidimensional.

-ou-

modifiers é multidimensional.

Observações

Embora o fichário padrão não processe ParameterModifier (o modifiers parâmetro), você pode usar a classe abstrata System.Reflection.Binder para escrever um fichário personalizado que processa modifiers. ParameterModifier é utilizado apenas ao fazer chamadas através da interoperabilidade COM, e apenas os parâmetros que são passados por referência são tratados.

A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui métodos públicos estáticos e de instância pública.

Note

Não podes omitir parâmetros ao procurar construtores e métodos. Só podes omitir parâmetros ao invocar.

Se o current Type representa um tipo genérico construído, esse método retorna o MethodInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.

Se a corrente Type representa um parâmetro de tipo na definição de um tipo genérico ou método genérico, este método pesquisa os métodos da restrição de classe, ou os métodos de Object se não houver restrição de classe.

Note

Para métodos genéricos, não inclua os argumentos tipo em name. Por exemplo, o código GetMethod("MyMethod<int>") C# procura um membro com o nome de texto "MyMethod<int>", em vez de um método nomeado MyMethod que tenha um argumento genérico do tipo int. Em vez disso, use GetMethod("MyMethod") com o parâmetro apropriado no types array.

Ver também

Aplica-se a