Type.GetMethod Método

Definición

Obtiene un método específico del objeto Type actual.

Sobrecargas

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

Busca el método especificado cuyos parámetros coincidan con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados, mediante las restricciones de enlace y la convención de llamada especificadas.

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

Busca el método especificado cuyos parámetros coincidan con los tipos y modificadores de argumentos especificados, usando las restricciones de enlace indicadas y la convención de llamada especificada.

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

Busca el método especificado cuyos parámetros coincidan con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados, mediante las restricciones de enlace especificadas.

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

Busca el método especificado cuyos parámetros coincidan con los tipos y modificadores de argumentos especificados, mediante las restricciones de enlace indicadas.

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

Busca el método público especificado cuyos parámetros coincidan con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados.

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

Busca el método especificado mediante las restricciones de enlace especificadas.

GetMethod(String, BindingFlags, Type[])

Busca el método especificado cuyos parámetros coinciden con los tipos de argumento especificados, utilizando las restricciones de enlace especificadas.

GetMethod(String, Int32, Type[])

Busca el método público especificado cuyos parámetros coincidan con el número de parámetros genéricos y los tipos de argumento especificados.

GetMethod(String, Type[])

Busca el método público especificado cuyos parámetros coincidan con los tipos de argumentos especificados.

GetMethod(String)

Busca el método público con el nombre especificado.

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

Busca el método público especificado cuyos parámetros coincidan con los tipos y modificadores de argumento especificados.

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

Busca el método especificado cuyos parámetros coincidan con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados, mediante las restricciones de enlace y la convención de llamada especificadas.

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);
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);
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

Cadena que contiene el nombre del método público que se va a obtener.

genericParameterCount
Int32

El número de parámetros de tipo genérico del método.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

O bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

callConvention
CallingConventions

Objeto que especifica el conjunto de reglas que van a usarse en cuanto al orden y diseño de los argumentos, la forma de pasar el valor devuelto, los registros que se usan para los argumentos y la forma en que se limpia la pila.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. Solo se ha de usar cuando se llama mediante la interoperabilidad COM y solo se controlan parámetros que se pasan por referencia. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Un objeto que representa el método que coincide con el número de parámetros genéricos, los tipos de argumento, los modificadores, las restricciones de enlace y la convención de llamada especificados, si se encuentra; en caso contrario, null.

Excepciones

name es null.

O bien

types es null.

O bien

Uno de los elementos de la matriz types es null.

genericParameterCount es negativo.

Se aplica a

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

Busca el método especificado cuyos parámetros coincidan con los tipos y modificadores de argumentos especificados, usando las restricciones de enlace indicadas y la convención de llamada 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);
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);
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

Cadena que contiene el nombre del método que se va a obtener.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

O bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

callConvention
CallingConventions

Objeto que especifica el conjunto de reglas que van a usarse en cuanto al orden y diseño de los argumentos, la forma de pasar el valor devuelto, los registros que se usan para los argumentos y la forma en que se limpia la pila.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. Solo se ha de usar cuando se llama mediante la interoperabilidad COM y solo se controlan parámetros que se pasan por referencia. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Objeto que representa el método que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encontró más de un método con el nombre especificado y que coincide con las restricciones de enlace especificadas.

name es null.

O bien

types es null.

O bien

Uno de los elementos de types es null.

types es multidimensional.

O bien

modifiers es multidimensional.

Ejemplos

En el ejemplo siguiente se buscan sobrecargas específicas de MethodA, que especifican restricciones de enlace, convenciones de llamada y una variedad de tipos de argumentos.

Nota

El ejemplo de Visual C# 2005 requiere la /unsafe opción del compilador.

using namespace System;
using namespace System::Reflection;

public ref class Program
{

public:
    // Methods to get:

    void MethodA(int i, int j) { }

    void MethodA(array<int>^ iarry) { }

    void MethodA(double *ip) { }

    // Method that takes a managed reference paramter.
    void MethodA(int% r) {}
};

int main()
{
    MethodInfo^ mInfo;


    // Get MethodA(int i, int j)
    mInfo = Program::typeid->GetMethod("MethodA",
        BindingFlags::Public | BindingFlags::Instance,
        nullptr,
        CallingConventions::Any,
        gcnew array<Type^> {int::typeid, int::typeid},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

    // Get  MethodA(array<int>^ iarry)
    mInfo = Program::typeid->GetMethod("MethodA",
        BindingFlags::Public | BindingFlags::Instance,
        nullptr,
        CallingConventions::Any,
        gcnew array<Type^> {int::typeid->MakeArrayType()},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(double *ip)
    mInfo = Program::typeid->GetMethod("MethodA",
        BindingFlags::Public | BindingFlags::Instance,
        nullptr,
        CallingConventions::Any,
        gcnew array<Type^> {double::typeid->MakePointerType()},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(int% r)
    mInfo = Program::typeid->GetMethod("MethodA",
        BindingFlags::Public | BindingFlags::Instance,
        nullptr,
        CallingConventions::Any,
        gcnew array<Type^> {int::typeid->MakeByRefType()},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

}

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

Comentarios

Aunque el enlazador predeterminado no procesa ParameterModifier (el modifiers parámetro ), puede usar la clase abstracta System.Reflection.Binder para escribir un enlazador personalizado que procesa modifiers. ParameterModifier solo se usa al llamar a través de la interoperabilidad COM y solo se controlan los parámetros que se pasan por referencia.

En la tabla siguiente se muestra qué miembros de una clase base devuelven los GetXXX métodos al reflejar en un tipo.

Tipo de miembro Estático No estático
Constructor No No
Campo No Sí. Un campo siempre se oculta por nombre y firma.
evento No es aplicable La regla del sistema de tipos común es que la herencia es la misma que la de los métodos que implementan la propiedad . La reflexión trata las propiedades como hide-by-name-and-signature. Consulte la nota 2 a continuación.
Método No Sí. Un método (tanto virtual como no virtual) puede ser hide-by-name u hide-by-name-and-signature.
Tipo anidado No No
Propiedad. No es aplicable La regla del sistema de tipos común es que la herencia es la misma que la de los métodos que implementan la propiedad . La reflexión trata las propiedades como hide-by-name-and-signature. Consulte la nota 2 a continuación.
  1. Hide-by-name-and-signature tiene en cuenta todas las partes de la firma, incluidos modificadores personalizados, tipos de valor devuelto, tipos de parámetros, sentinels y convenciones de llamada no administradas. Se trata de una comparación binaria.

  2. En el caso de la reflexión, las propiedades y los eventos son hide-by-name-and-signature. Si tiene una propiedad con un descriptor de acceso get y un set en la clase base, pero la clase derivada solo tiene un descriptor de acceso get, la propiedad de clase derivada oculta la propiedad de clase base y no podrá acceder al establecedor en la clase base.

  3. Los atributos personalizados no forman parte del sistema de tipos común.

Las marcas de filtro siguientes BindingFlags se pueden usar para definir qué métodos se van a incluir en la búsqueda:

  • Debe especificar o BindingFlags.InstanceBindingFlags.Static para obtener una devolución.

  • Especifique BindingFlags.Public para incluir métodos públicos en la búsqueda.

  • Especifique BindingFlags.NonPublic que incluya métodos no públicos (es decir, métodos privados, internos y protegidos) en la búsqueda.

  • Especifique BindingFlags.FlattenHierarchy para incluir y protected miembros public estáticos en la jerarquía; private no se incluyen los miembros estáticos de las clases heredadas.

Se pueden usar las marcas modificadores siguientes BindingFlags para cambiar el funcionamiento de la búsqueda:

  • BindingFlags.IgnoreCase para pasar por alto el caso de name.

  • BindingFlags.DeclaredOnly para buscar solo los métodos declarados en , Typeno los métodos que simplemente se heredaron.

Vea System.Reflection.BindingFlags para obtener más información.

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con MethodInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en los métodos de la restricción de clase o en los métodos de si no hay ninguna restricción de Object clase.

Nota

Para los métodos genéricos, no incluya los argumentos de tipo en name. Por ejemplo, el código GetMember("MyMethod<int>") de C# busca un miembro con el nombre de texto "MyMethod<int>", en lugar de para un método denominado MyMethod que tiene un argumento genérico de tipo int.

Consulte también

Se aplica a

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

Busca el método especificado cuyos parámetros coincidan con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados, mediante las restricciones de enlace 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);
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);
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

Cadena que contiene el nombre del método público que se va a obtener.

genericParameterCount
Int32

El número de parámetros de tipo genérico del método.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

O bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. Solo se ha de usar cuando se llama mediante la interoperabilidad COM y solo se controlan parámetros que se pasan por referencia. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Un objeto que representa el método público que coincide con el número de parámetros genéricos, los tipos de argumento, los modificadores y las restricciones de enlace especificados, si se encuentra; en caso contrario, null.

Excepciones

name es null.

O bien

types es null.

O bien

Uno de los elementos de la matriz types es null.

genericParameterCount es negativo.

Se aplica a

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

Busca el método especificado cuyos parámetros coincidan con los tipos y modificadores de argumentos especificados, mediante las restricciones de enlace indicadas.

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);
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);
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

Cadena que contiene el nombre del método que se va a obtener.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

O bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. Solo se ha de usar cuando se llama mediante la interoperabilidad COM y solo se controlan parámetros que se pasan por referencia. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Objeto que representa el método que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encontró más de un método con el nombre especificado y que coincide con las restricciones de enlace especificadas.

name es null.

O bien

types es null.

O bien

Uno de los elementos de types es null.

types es multidimensional.

O bien

modifiers es multidimensional.

Ejemplos

En el ejemplo siguiente se buscan sobrecargas específicas de MethodA, especificando restricciones de enlace y una variedad de tipos de argumentos.

Nota

El ejemplo de Visual C# 2005 requiere la /unsafe opción del compilador.

using namespace System;
using namespace System::Reflection;

public ref class Program
{

public:
    // Methods to get:

    void MethodA(int i, int j) { }

    void MethodA(array<int>^ iarry) { }

    void MethodA(double *ip) { }

    // Method that takes a managed reference parameter.
    void MethodA(int% r) {}
};

int main()
{
    MethodInfo^ mInfo;


    // Get MethodA(int i, int j)
    mInfo = Program::typeid->GetMethod("MethodA",
        static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance),
        nullptr,
        gcnew array<Type^> {int::typeid, int::typeid},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

    // Get  MethodA(array<int>^ iarry)
    mInfo = Program::typeid->GetMethod("MethodA",
        static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance),
        nullptr,
        gcnew array<Type^> {int::typeid->MakeArrayType()},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(double *ip)
    mInfo = Program::typeid->GetMethod("MethodA",
        static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance),
        nullptr,
        gcnew array<Type^> {double::typeid->MakePointerType()},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(int% r)
    mInfo = Program::typeid->GetMethod("MethodA",
        static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance),
        nullptr,
        gcnew array<Type^> {int::typeid->MakeByRefType()},
        nullptr);
    Console::WriteLine("Found method: {0}", mInfo );
}

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

Comentarios

Aunque el enlazador predeterminado no procesa ParameterModifier (el modifiers parámetro ), puede usar la clase abstracta System.Reflection.Binder para escribir un enlazador personalizado que procese modifiers. ParameterModifier solo se usa al llamar a través de la interoperabilidad COM y solo se controlan los parámetros que se pasan por referencia.

Las marcas de filtro siguientes BindingFlags se pueden usar para definir qué métodos se van a incluir en la búsqueda:

  • Debe especificar o BindingFlags.InstanceBindingFlags.Static para obtener una devolución.

  • Especifique BindingFlags.Public para incluir métodos públicos en la búsqueda.

  • Especifique BindingFlags.NonPublic que incluya métodos no públicos (es decir, métodos privados, internos y protegidos) en la búsqueda.

  • Especifique BindingFlags.FlattenHierarchy para incluir y protected miembros public estáticos en la jerarquía; private no se incluyen los miembros estáticos de las clases heredadas.

Se pueden usar las marcas modificadores siguientes BindingFlags para cambiar el funcionamiento de la búsqueda:

  • BindingFlags.IgnoreCase para pasar por alto el caso de name.

  • BindingFlags.DeclaredOnly para buscar solo los métodos declarados en , Typeno los métodos que simplemente se heredaron.

Vea System.Reflection.BindingFlags para obtener más información.

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con MethodInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en los métodos de la restricción de clase o en los métodos de si no hay ninguna restricción de Object clase.

Nota

Para los métodos genéricos, no incluya los argumentos de tipo en name. Por ejemplo, el código GetMember("MyMethod<int>") de C# busca un miembro con el nombre de texto "MyMethod<int>", en lugar de para un método denominado MyMethod que tiene un argumento genérico de tipo int.

Consulte también

Se aplica a

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

Busca el método público especificado cuyos parámetros coincidan con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, cli::array <Type ^> ^ types, cli::array <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);
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

Cadena que contiene el nombre del método público que se va a obtener.

genericParameterCount
Int32

El número de parámetros de tipo genérico del método.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. Solo se ha de usar cuando se llama mediante la interoperabilidad COM y solo se controlan parámetros que se pasan por referencia. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Un objeto que representa el método público que coincide con el número de parámetros genéricos, los tipos de argumento y los modificadores especificados, si se encuentra; en caso contrario, null.

Excepciones

name es null.

O bien

types es null.

O bien

Uno de los elementos de la matriz types es null.

genericParameterCount es negativo.

Se aplica a

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

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
public System.Reflection.MethodInfo? GetMethod (string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, Type[] types);
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
genericParameterCount
Int32
bindingAttr
BindingFlags
types
Type[]

Devoluciones

Se aplica a

GetMethod(String, BindingFlags)

Busca el método especificado mediante las restricciones de enlace especificadas.

public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::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);
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

Cadena que contiene el nombre del método que se va a obtener.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

Devoluciones

Objeto que representa el método que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encontró más de un método con el nombre especificado y que coincide con las restricciones de enlace especificadas.

name es null.

Ejemplos

En el ejemplo siguiente se obtiene el método que coincide con las marcas de enlace especificadas.

using namespace System;
using namespace System::Reflection;
public ref class Program
{

    public:

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

    };

    int main()
    {

        // Get MethodA()
        MethodInfo^ mInfo = Program::typeid->GetMethod("MethodA",
            static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance));
        Console::WriteLine("Found method: {0}", mInfo );

    }
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

Comentarios

Las marcas de filtro siguientes BindingFlags se pueden usar para definir qué métodos se van a incluir en la búsqueda:

Se pueden usar las marcas modificadores siguientes BindingFlags para cambiar el funcionamiento de la búsqueda:

Vea System.Reflection.BindingFlags para obtener más información.

Si un método está sobrecargado y más de una sobrecarga cumple las restricciones especificadas por el bindingAttr argumento , el método produce una AmbiguousMatchException excepción. En el ejemplo siguiente, se produce una excepción porque:

  • El TestClass tipo tiene dos sobrecargas de instancia pública del DisplayValue método y DisplayValue(String)DisplayValue(String, Object[]).

  • El TestClass tipo tiene dos sobrecargas de instancia pública del Equals método , una de las cuales se hereda de Object: Equals(TestClass) y 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)

Puede realizar una de las siguientes acciones para recuperar un método específico:

  • Cambie las restricciones de enlace. En el ejemplo anterior, al intentar recuperar un método de instancia Equals pública declarado por el tipo y que no se hereda correctamente, se recupera Equals(TestClass).

  • Llame a una sobrecarga del GetMethod método que incluye un types parámetro que define los tipos de los parámetros del método.

  • Llame al GetMethods(BindingFlags) método para recuperar una matriz que contenga todos los métodos que pertenecen a un tipo que tenga los atributos de enlace especificados. A continuación, puede iterar para identificar los métodos duplicados denominados name. Este enfoque se muestra en el controlador del ejemplo anterior para la AmbiguousMatchException excepción.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con MethodInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en los métodos de la restricción de clase o en los métodos de si no hay ninguna restricción de Object clase.

Nota

Para los métodos genéricos, no incluya los argumentos de tipo en name. Por ejemplo, el código GetMember("MyMethod<int>") de C# busca un miembro con el nombre de texto "MyMethod<int>", en lugar de para un método denominado MyMethod que tiene un argumento genérico de tipo int.

Consulte también

Se aplica a

GetMethod(String, BindingFlags, Type[])

Busca el método especificado cuyos parámetros coinciden con los tipos de argumento especificados, utilizando las restricciones de enlace especificadas.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
public System.Reflection.MethodInfo? GetMethod (string name, System.Reflection.BindingFlags bindingAttr, Type[] types);
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

Cadena que contiene el nombre del método que se va a obtener.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda. -o bien- Valor predeterminado para devolver null.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener. -o bien- Matriz vacía de Type objetos (según lo proporcionado por el EmptyTypes campo) para obtener un método que no toma parámetros.

Devoluciones

Objeto que representa el método que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Se aplica a

GetMethod(String, Int32, Type[])

Busca el método público especificado cuyos parámetros coincidan con el número de parámetros genéricos y los tipos de argumento especificados.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name, int genericParameterCount, cli::array <Type ^> ^ types);
public System.Reflection.MethodInfo? GetMethod (string name, int genericParameterCount, Type[] types);
public System.Reflection.MethodInfo GetMethod (string name, int genericParameterCount, Type[] types);
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

Cadena que contiene el nombre del método público que se va a obtener.

genericParameterCount
Int32

El número de parámetros de tipo genérico del método.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

Devoluciones

Un objeto que representa el método público cuyos parámetros coinciden con el número de parámetros genéricos y los tipos de argumento especificados, si se encuentra; en caso contrario, null.

Excepciones

name es null.

O bien

types es null.

O bien

Uno de los elementos de la matriz types es null.

genericParameterCount es negativo.

Se aplica a

GetMethod(String, Type[])

Busca el método público especificado cuyos parámetros coincidan con los tipos de argumentos 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);
public System.Reflection.MethodInfo? GetMethod (string name, Type[] types);
public System.Reflection.MethodInfo GetMethod (string name, Type[] types);
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

Cadena que contiene el nombre del método público que se va a obtener.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

Devoluciones

Objeto que representa el método público cuyos parámetros coinciden con los tipos de argumentos especificados, si se encuentra; en caso contrario, null.

Implementaciones

Excepciones

Se encuentra más de un método con el nombre y los parámetros especificados.

name es null.

O bien

types es null.

O bien

Uno de los elementos de types es null.

types es multidimensional.

Ejemplos

En el ejemplo siguiente se buscan sobrecargas específicas de MethodA, especificando una variedad de tipos de argumentos.

Nota

El ejemplo de Visual C# 2005 requiere la /unsafe opción del compilador.

using namespace System;
using namespace System::Reflection;

public ref class Program
{

public:
    // Methods to get:

    void MethodA(int i, int j) { }

    void MethodA(array<int>^ iarry) { }

    void MethodA(double *ip) { }

    // Method that takes a managed reference parameter.
    void MethodA(int% r) {}
};

int main()
{
    MethodInfo^ mInfo;


    // Get MethodA(int i, int j)
    mInfo = Program::typeid->GetMethod("MethodA", gcnew array<Type^> {int::typeid,int::typeid});
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(array<int>^ iarry)
    mInfo = Program::typeid->GetMethod("MethodA", gcnew array<Type^> {int::typeid->MakeArrayType()});
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(double *ip)
    mInfo = Program::typeid->GetMethod("MethodA", gcnew array<Type^> {double::typeid->MakePointerType()});
    Console::WriteLine("Found method: {0}", mInfo );

    // Get MethodA(int% r)
    mInfo = Program::typeid->GetMethod("MethodA", gcnew array<Type^> {int::typeid->MakeByRefType()});
    // Display the method information.
    Console::WriteLine("Found method: {0}", mInfo );

}

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

En el ejemplo siguiente se recuperan MethodInfo objetos que representan los Add métodos de un tipo no genérico (la ArrayList clase), un tipo genérico abierto (la List<T> clase) y un tipo genérico cerrado (el 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)

En el ejemplo se define un GetAddMethod método que recupera el objeto adecuado MethodInfo . Para proporcionar el types argumento para un tipo genérico abierto, llama al Type.GetGenericArguments método . Para proporcionar el types argumento para un tipo genérico cerrado, recupera el valor de la Type.GenericTypeArguments propiedad .

Comentarios

La búsqueda distingue name mayúsculas de minúsculas. La búsqueda incluye métodos de instancia pública estática y pública.

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con MethodInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en los métodos de la restricción de clase o en los métodos de si no hay ninguna restricción de Object clase.

Nota

El name parámetro no puede incluir argumentos de tipo. Por ejemplo, el código GetMethod("MyGenericMethod<int>") de C# busca un método con el nombre de texto "MyGenericMethod<int>", en lugar de para un método denominado MyGenericMethod que tiene un argumento genérico de tipo int. En su lugar, use GetMethod("MyGenericMethod") con el parámetro adecuado en la types matriz.

Consulte también

Se aplica a

GetMethod(String)

Busca el método público con el nombre especificado.

public:
 System::Reflection::MethodInfo ^ GetMethod(System::String ^ name);
public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name);
public System.Reflection.MethodInfo? GetMethod (string name);
public System.Reflection.MethodInfo GetMethod (string name);
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

Cadena que contiene el nombre del método público que se va a obtener.

Devoluciones

Objeto que representa al método público con el nombre especificado, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encontró más de un método con el nombre especificado.

name es null.

Ejemplos

En el ejemplo siguiente se obtiene un método denominado MethodA.

using namespace System;
using namespace System::Reflection;
public ref class Program
{

    public:

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

    };

    int main()
    {

        // Get MethodA()
        MethodInfo^ mInfo = Program::typeid->GetMethod("MethodA");
        Console::WriteLine("Found method: {0}", mInfo );

    }

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

Comentarios

La búsqueda name distingue mayúsculas de minúsculas. La búsqueda incluye métodos de instancia pública estática y pública.

Si un método está sobrecargado y tiene más de un método público, el GetMethod(String) método produce una AmbiguousMatchException excepción. En el ejemplo siguiente, se produce una excepción porque hay más de una sobrecarga pública del Int32.ToString método . Por otro lado, dado que el Person.ToString método invalida Object.ToString y, por lo tanto, no está sobrecargado, el GetMethod(String) método puede recuperar el 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.

Puede realizar una de las siguientes acciones para recuperar un método específico:

  • Llame al GetMethod(String, BindingFlags) método y especifique un bindingAttr argumento que identifique de forma única el método. Por ejemplo, si se produce la excepción porque un tipo tiene una sobrecarga estática y de instancia, puede especificar un bindingAttr argumento deOrBindingFlags.InstanceBindingFlags.Instance .

  • Llame a una sobrecarga del GetMethod método que incluye un types parámetro que define los tipos de los parámetros del método.

  • Llame al GetMethods() método para recuperar una matriz que contenga todos los métodos públicos que pertenecen a un tipo. Después, puede iterar para identificar los métodos duplicados denominados name.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con MethodInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en los métodos de la restricción de clase o en los métodos de si no hay ninguna restricción de Object clase.

Nota

En el caso de los métodos genéricos, no incluya los argumentos de tipo en name. Por ejemplo, el código GetMember("MyMethod<int>") de C# busca un miembro con el nombre de texto "MyMethod<int>", en lugar de para un método denominado MyMethod que tiene un argumento genérico de tipo int.

Consulte también

Se aplica a

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

Busca el método público especificado cuyos parámetros coincidan con los tipos y modificadores de argumento 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);
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);
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

Cadena que contiene el nombre del método público que se va a obtener.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el método debe obtener.

O bien

Una matriz vacía de objetos Type (proporcionados por el campo EmptyTypes) para obtener un método que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. Solo se ha de usar cuando se llama mediante la interoperabilidad COM y solo se controlan parámetros que se pasan por referencia. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Objeto que representa el método público que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encuentra más de un método con el nombre y los parámetros especificados.

name es null.

O bien

types es null.

O bien

Uno de los elementos de types es null.

types es multidimensional.

O bien

modifiers es multidimensional.

Comentarios

Aunque el enlazador predeterminado no procesa ParameterModifier (el modifiers parámetro ), puede usar la clase abstracta System.Reflection.Binder para escribir un enlazador personalizado que procesa modifiers. ParameterModifier solo se usa al llamar a través de la interoperabilidad COM y solo se controlan los parámetros que se pasan por referencia.

La búsqueda name distingue mayúsculas de minúsculas. La búsqueda incluye métodos de instancia pública estática y pública.

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir los parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con MethodInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en los métodos de la restricción de clase o en los métodos de si no hay ninguna restricción de Object clase.

Nota

En el caso de los métodos genéricos, no incluya los argumentos de tipo en name. Por ejemplo, el código GetMethod("MyMethod<int>") de C# busca un miembro con el nombre de texto "MyMethod<int>", en lugar de para un método denominado MyMethod que tiene un argumento genérico de tipo int. En su lugar, use GetMethod("MyMethod") con el parámetro adecuado en la types matriz.

Consulte también

Se aplica a