Type.GetMethod Metodo

Definizione

Ottiene un metodo specifico dell'oggetto Type corrente.

Overload

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

Cerca il metodo specificato i cui parametri corrispondono al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding e la convenzione di chiamata specificati.

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

Cerca il metodo specificato i cui parametri corrispondono ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding e la convenzione di chiamata specificati.

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

Cerca il metodo specificato i cui parametri corrispondono al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding specificati.

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

Cerca il metodo specificato i cui parametri corrispondono ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding specificati.

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

Cerca il metodo pubblico specificato i cui parametri corrispondono al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati.

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

Cerca il metodo specificato, usando i vincoli di binding specificati.

GetMethod(String, BindingFlags, Type[])

Cerca il metodo specificato i cui parametri corrispondono ai tipi di argomento specificati, utilizzando i vincoli di associazione specificati.

GetMethod(String, Int32, Type[])

Cerca il metodo pubblico specificato i cui parametri corrispondono al numero di parametri generici e ai tipi di argomenti specificati.

GetMethod(String, Type[])

Cerca il metodo pubblico specificato i cui parametri corrispondono ai tipi di argomenti specificati.

GetMethod(String)

Cerca il metodo pubblico con il nome specificato.

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

Cerca il metodo pubblico specificato i cui parametri corrispondono ai modificatori e ai tipi di argomenti specificati.

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

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo specificato i cui parametri corrispondono al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding e la convenzione di chiamata specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

genericParameterCount
Int32

Numero di parametri di tipo generico del metodo.

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

binder
Binder

Oggetto che definisce una serie di proprietà e permette il binding, che può implicare la scelta di un metodo di overload, la coercizione di tipi di argomento e la chiamata di un membro mediante reflection.

-oppure-

Riferimento Null (Nothing in Visual Basic) per l'uso di DefaultBinder.

callConvention
CallingConventions

Oggetto che specifica il set di regole da usare per la disposizione e il layout degli argomenti, la modalità di passaggio del valore restituito, i registri usati per gli argomenti e la pulizia dello stack.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Da usare solo quando si effettuano chiamate tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il metodo corrispondente al numero di parametri generici, ai tipi di argomento, ai modificatori, ai vincoli di binding e alla convenzione di chiamata specificati, se viene trovato. In caso contrario, null.

Eccezioni

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi nella matrice types è null.

genericParameterCount è negativo.

Si applica a

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

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo specificato i cui parametri corrispondono ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding e la convenzione di chiamata specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo da ottenere.

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

binder
Binder

Oggetto che definisce una serie di proprietà e permette il binding, che può implicare la scelta di un metodo di overload, la coercizione di tipi di argomento e la chiamata di un membro mediante reflection.

-oppure-

Riferimento Null (Nothing in Visual Basic) per l'uso di DefaultBinder.

callConvention
CallingConventions

Oggetto che specifica il set di regole da usare per la disposizione e il layout degli argomenti, la modalità di passaggio del valore restituito, i registri usati per gli argomenti e la pulizia dello stack.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Da usare solo quando si effettuano chiamate tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il metodo corrispondente ai requisiti specificati, se presente; in caso contrario, null.

Implementazioni

Eccezioni

È stato trovato più di un metodo con il nome specificato e corrispondente ai vincoli di associazione specificati.

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

-oppure-

modifiers è multidimensionale.

Esempio

Nell'esempio seguente vengono trovati overload specifici di , specificando vincoli di MethodAassociazione, convenzioni di chiamata e un'ampia gamma di tipi di argomento.

Nota

L'esempio di Visual C# 2005 richiede l'opzione del /unsafe compilatore.

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

Commenti

Anche se il binder predefinito non elabora ParameterModifier (il parametro ), è possibile usare la classe astratta System.Reflection.Binder per scrivere un binder personalizzato che esegue l'elaborazione modifiersmodifiersdi . ParameterModifier viene usato solo quando si chiama tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento.

Nella tabella seguente vengono illustrati i membri di una classe base restituiti dai GetXXX metodi quando si riflette su un tipo.

Tipo di membro Static Non statico
Costruttore No No
Campo No Sì. Un campo è sempre hide-by-name-and-signature.
Evento Non applicabile La regola di sistema dei tipi comune è che l'ereditarietà è uguale a quella dei metodi che implementano la proprietà . La reflection considera le proprietà come hide-by-name-and-signature. Vedere la nota 2 di seguito.
Metodo No Sì. Un metodo (sia virtuale che non virtuale) può essere hide-by-name o hide-by-name-and-signature.
Tipo annidato No No
Proprietà Non applicabile La regola di sistema dei tipi comune è che l'ereditarietà è uguale a quella dei metodi che implementano la proprietà . La reflection considera le proprietà come hide-by-name-and-signature. Vedere la nota 2 di seguito.
  1. Hide-by-name-and-signature considera tutte le parti della firma, inclusi modificatori personalizzati, tipi restituiti, tipi di parametro, sentinel e convenzioni di chiamata non gestite. Si tratta di un confronto binario.

  2. Per la reflection, le proprietà e gli eventi sono hide-by-name-and-signature. Se nella classe base è presente una proprietà con una funzione di accesso get e una funzione di accesso set, ma la classe derivata ha solo una funzione di accesso get, la proprietà della classe derivata nasconde la proprietà della classe base e non sarà possibile accedere al setter nella classe base.

  3. Gli attributi personalizzati non fanno parte del sistema di tipi comuni.

È possibile usare i flag di filtro seguenti BindingFlags per definire i metodi da includere nella ricerca:

  • È necessario specificare BindingFlags.Instance o BindingFlags.Static per ottenere un ritorno.

  • Specificare BindingFlags.Public per includere i metodi pubblici nella ricerca.

  • Specificare BindingFlags.NonPublic di includere metodi non pubblici (ovvero metodi privati, interni e protetti) nella ricerca.

  • Specificare BindingFlags.FlattenHierarchy di includere public e protected membri statici fino alla gerarchia. private I membri statici nelle classi ereditate non sono inclusi.

Per modificare il funzionamento della ricerca, è possibile usare i flag di modificatore seguenti BindingFlags :

  • BindingFlags.IgnoreCase per ignorare il caso di name.

  • BindingFlags.DeclaredOnly per cercare solo i metodi dichiarati in Type, non i metodi semplicemente ereditati.

Per altre informazioni, vedere System.Reflection.BindingFlags.

Nota

Non è possibile omettere parametri durante la ricerca di costruttori e metodi. È possibile omettere i parametri solo quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con MethodInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i metodi del vincolo di classe o i metodi di se non è presente alcun vincolo di Object classe.

Nota

Per i metodi generici, non includere gli argomenti di tipo in name. Ad esempio, il codice GetMember("MyMethod<int>") C# cerca un membro con il nome di testo "MyMethod<int>", anziché un metodo denominato MyMethod con un argomento generico di tipo int.

Vedi anche

Si applica a

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

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo specificato i cui parametri corrispondono al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

genericParameterCount
Int32

Numero di parametri di tipo generico del metodo.

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

binder
Binder

Oggetto che definisce una serie di proprietà e permette il binding, che può implicare la scelta di un metodo di overload, la coercizione di tipi di argomento e la chiamata di un membro mediante reflection.

-oppure-

Riferimento Null (Nothing in Visual Basic) per l'uso di DefaultBinder.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Da usare solo quando si effettuano chiamate tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il metodo corrispondente al numero di parametri generici, ai tipi di argomento, ai modificatori e ai vincoli di binding specificati, se viene trovato. In caso contrario, null.

Eccezioni

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi nella matrice types è null.

genericParameterCount è negativo.

Si applica a

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

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo specificato i cui parametri corrispondono ai tipi di argomenti e ai modificatori specificati, usando i vincoli di binding specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo da ottenere.

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

binder
Binder

Oggetto che definisce una serie di proprietà e permette il binding, che può implicare la scelta di un metodo di overload, la coercizione di tipi di argomento e la chiamata di un membro mediante reflection.

-oppure-

Riferimento Null (Nothing in Visual Basic) per l'uso di DefaultBinder.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Da usare solo quando si effettuano chiamate tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il metodo corrispondente ai requisiti specificati, se presente; in caso contrario, null.

Implementazioni

Eccezioni

È stato trovato più di un metodo con il nome specificato e corrispondente ai vincoli di associazione specificati.

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

-oppure-

modifiers è multidimensionale.

Esempio

Nell'esempio seguente vengono trovati overload specifici di , specificando i vincoli di MethodAassociazione e un'ampia gamma di tipi di argomento.

Nota

L'esempio di Visual C# 2005 richiede l'opzione del /unsafe compilatore.

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

Commenti

Anche se il binder predefinito non elabora ParameterModifier (il parametro ), è possibile usare la classe astratta System.Reflection.Binder per scrivere un binder personalizzato che esegue l'elaborazione modifiersmodifiersdi . ParameterModifier viene usato solo quando si chiama tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento.

È possibile usare i flag di filtro seguenti BindingFlags per definire i metodi da includere nella ricerca:

  • È necessario specificare BindingFlags.Instance o BindingFlags.Static per ottenere un ritorno.

  • Specificare BindingFlags.Public per includere i metodi pubblici nella ricerca.

  • Specificare BindingFlags.NonPublic di includere metodi non pubblici (ovvero metodi privati, interni e protetti) nella ricerca.

  • Specificare BindingFlags.FlattenHierarchy di includere public e protected membri statici fino alla gerarchia. private I membri statici nelle classi ereditate non sono inclusi.

Per modificare il funzionamento della ricerca, è possibile usare i flag di modificatore seguenti BindingFlags :

  • BindingFlags.IgnoreCase per ignorare il caso di name.

  • BindingFlags.DeclaredOnly per cercare solo i metodi dichiarati in Type, non i metodi semplicemente ereditati.

Per altre informazioni, vedere System.Reflection.BindingFlags.

Nota

Non è possibile omettere parametri durante la ricerca di costruttori e metodi. È possibile omettere i parametri solo quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con MethodInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i metodi del vincolo di classe o i metodi di se non è presente alcun vincolo di Object classe.

Nota

Per i metodi generici, non includere gli argomenti di tipo in name. Ad esempio, il codice GetMember("MyMethod<int>") C# cerca un membro con il nome di testo "MyMethod<int>", anziché un metodo denominato MyMethod con un argomento generico di tipo int.

Vedi anche

Si applica a

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

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo pubblico specificato i cui parametri corrispondono al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

genericParameterCount
Int32

Numero di parametri di tipo generico del metodo.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Da usare solo quando si effettuano chiamate tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il metodo pubblico corrispondente al numero di parametri generici, ai tipi di argomenti e ai modificatori specificati, se viene trovato. In caso contrario, null.

Eccezioni

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi nella matrice types è null.

genericParameterCount è negativo.

Si applica a

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

Source:
Type.cs
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

Parametri

name
String
genericParameterCount
Int32
bindingAttr
BindingFlags
types
Type[]

Restituisce

Si applica a

GetMethod(String, BindingFlags)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo specificato, usando i vincoli di binding specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo da ottenere.

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

Restituisce

Oggetto che rappresenta il metodo corrispondente ai requisiti specificati, se presente; in caso contrario, null.

Implementazioni

Eccezioni

È stato trovato più di un metodo con il nome specificato e corrispondente ai vincoli di associazione specificati.

name è null.

Esempio

L'esempio seguente ottiene il metodo che corrisponde ai flag di associazione specificati.

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

Commenti

I flag di filtro seguenti BindingFlags possono essere usati per definire i metodi da includere nella ricerca:

I flag di modifica seguenti BindingFlags possono essere usati per modificare il funzionamento della ricerca:

Per altre informazioni, vedere System.Reflection.BindingFlags.

Se un metodo viene sovraccaricato e più di un overload soddisfa i vincoli specificati dall'argomento, il metodo genera un'eccezione bindingAttrAmbiguousMatchException . Nell'esempio seguente viene generata un'eccezione perché:

  • Il TestClass tipo ha due overload di istanza pubblica del DisplayValue metodo DisplayValue(String) e DisplayValue(String, Object[]).

  • Il TestClass tipo ha due overload di istanza pubblica del Equals metodo, uno dei quali viene ereditato da 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)

È possibile eseguire una delle operazioni seguenti per recuperare un metodo specifico:

  • Modificare i vincoli di associazione. Nell'esempio precedente, il tentativo di recuperare un metodo di istanza Equals pubblica dichiarato dal tipo e non ereditato recupera Equals(TestClass)correttamente .

  • Chiamare un overload del GetMethod metodo che include un types parametro che definisce i tipi dei parametri del metodo.

  • Chiamare il GetMethods(BindingFlags) metodo per recuperare una matrice contenente tutti i metodi appartenenti a un tipo con gli attributi di associazione specificati. È quindi possibile eseguirne l'iterazione per identificare i metodi duplicati denominati name. Questo approccio viene illustrato nel gestore dell'esempio precedente per l'eccezione AmbiguousMatchException .

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con MethodInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i metodi del vincolo di classe o i metodi di Object se non esiste alcun vincolo di classe.

Nota

Per i metodi generici, non includere gli argomenti di tipo in name. Ad esempio, il codice GetMember("MyMethod<int>") C# cerca un membro con il nome di testo "MyMethod<int>", anziché per un metodo denominato MyMethod con un argomento generico di tipo int.

Vedi anche

Si applica a

GetMethod(String, BindingFlags, Type[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo specificato i cui parametri corrispondono ai tipi di argomenti specificati usando i vincoli di associazione specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo da ottenere.

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca. -o- Impostazione predefinita per restituire null.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere. -o- Matrice vuota di Type oggetti (come fornito dal EmptyTypes campo) per ottenere un metodo che non accetta parametri.

Restituisce

Oggetto che rappresenta il metodo corrispondente ai requisiti specificati, se presente; in caso contrario, null.

Si applica a

GetMethod(String, Int32, Type[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo pubblico specificato i cui parametri corrispondono al numero di parametri generici e ai tipi di argomenti specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

genericParameterCount
Int32

Numero di parametri di tipo generico del metodo.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

Restituisce

Oggetto che rappresenta il metodo pubblico i cui parametri corrispondono al numero di parametrici generici e ai tipi di argomenti specificati, se viene trovato. In caso contrario, null.

Eccezioni

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi nella matrice types è null.

genericParameterCount è negativo.

Si applica a

GetMethod(String, Type[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo pubblico specificato i cui parametri corrispondono ai tipi di argomenti specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

Restituisce

Oggetto che rappresenta il metodo pubblico i cui parametri corrispondono ai tipi di argomenti specificati, se è stato trovato; in caso contrario, null.

Implementazioni

Eccezioni

Sono stati trovati più metodi con il nome e i parametri specificati.

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

Esempio

Nell'esempio seguente vengono trovati overload specifici di MethodA, specificando un'ampia gamma di tipi di argomenti.

Nota

L'esempio visual C# 2005 richiede l'opzione del /unsafe compilatore.

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

Nell'esempio seguente vengono recuperati MethodInfo oggetti che rappresentano i Add metodi di un tipo non generico (la ArrayList classe), un tipo generico aperto (la List<T> classe) e un tipo generico chiuso (il 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)

Nell'esempio viene definito un GetAddMethod metodo che recupera l'oggetto appropriato MethodInfo . Per specificare l'argomento types per un tipo generico aperto, chiama il Type.GetGenericArguments metodo . Per specificare l'argomento types per un tipo generico chiuso, recupera il valore della Type.GenericTypeArguments proprietà.

Commenti

La ricerca name è distinzione tra maiuscole e minuscole. La ricerca include metodi di istanza statica e pubblica pubblici.

Nota

Non è possibile omettere i parametri durante la ricerca di costruttori e metodi. È possibile omettere solo i parametri quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con MethodInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i metodi del vincolo di classe o i metodi di Object se non esiste alcun vincolo di classe.

Nota

Il name parametro non può includere argomenti di tipo. Ad esempio, il codice GetMethod("MyGenericMethod<int>") C# cerca un metodo con il nome di testo "MyGenericMethod<int>", anziché per un metodo denominato MyGenericMethod con un argomento generico di tipo int. Usare GetMethod("MyGenericMethod") invece con il parametro appropriato nella types matrice.

Vedi anche

Si applica a

GetMethod(String)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo pubblico con il nome specificato.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

Restituisce

Oggetto che rappresenta il metodo pubblico con il nome specificato, se è stato trovato; in caso contrario, null.

Implementazioni

Eccezioni

È stato trovato più di un metodo con il nome specificato.

name è null.

Esempio

L'esempio seguente ottiene un metodo denominato 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

Commenti

La ricerca name fa distinzione tra maiuscole e minuscole. La ricerca include metodi di istanza pubblica statica e pubblica.

Se un metodo è sottoposto a overload e ha più di un metodo pubblico, il GetMethod(String) metodo genera un'eccezione AmbiguousMatchException . Nell'esempio seguente viene generata un'eccezione perché è presente più di un overload pubblico del Int32.ToString metodo . D'altra parte, poiché il metodo esegue l'override Person.ToStringObject.ToString e pertanto non è sottoposto a overload, il GetMethod(String) metodo è in grado di recuperare l'oggetto MethodInfo .

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.

Per recuperare un metodo specifico, è possibile eseguire una delle operazioni seguenti:

  • Chiamare il GetMethod(String, BindingFlags) metodo e specificare un bindingAttr argomento che identifica in modo univoco il metodo . Ad esempio, se l'eccezione viene generata perché un tipo ha un overload statico e un overload di istanza, è possibile specificare un bindingAttr argomento diOrBindingFlags.InstanceBindingFlags.Instance .

  • Chiamare un overload del GetMethod metodo che include un types parametro che definisce i tipi dei parametri del metodo.

  • Chiamare il GetMethods() metodo per recuperare una matrice contenente tutti i metodi pubblici appartenenti a un tipo. È quindi possibile eseguire l'iterazione per identificare i metodi duplicati denominati name.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con MethodInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i metodi del vincolo di classe o i metodi di se non è presente alcun vincolo di Object classe.

Nota

Per i metodi generici, non includere gli argomenti di tipo in name. Ad esempio, il codice GetMember("MyMethod<int>") C# cerca un membro con il nome di testo "MyMethod<int>", anziché un metodo denominato MyMethod con un argomento generico di tipo int.

Vedi anche

Si applica a

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

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Cerca il metodo pubblico specificato i cui parametri corrispondono ai modificatori e ai tipi di argomenti specificati.

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

Parametri

name
String

Stringa che contiene il nome del metodo pubblico da ottenere.

types
Type[]

Matrice di oggetti Type che rappresentano numero, ordine e tipo dei parametri relativi al metodo da ottenere.

-oppure-

Matrice vuota di oggetti Type (come fornita dal campo EmptyTypes) per ottenere un metodo che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Da usare solo quando si effettuano chiamate tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il metodo pubblico corrispondente ai requisiti specificati, se è stato trovato; in caso contrario, null.

Implementazioni

Eccezioni

Sono stati trovati più metodi con il nome e i parametri specificati.

name è null.

-oppure-

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

-oppure-

modifiers è multidimensionale.

Commenti

Anche se il binder predefinito non elabora ParameterModifier (il parametro ), è possibile usare la classe astratta System.Reflection.Binder per scrivere un binder personalizzato che esegue l'elaborazione modifiersmodifiersdi . ParameterModifier viene usato solo quando si chiama tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento.

La ricerca name fa distinzione tra maiuscole e minuscole. La ricerca include metodi di istanza pubblica statica e pubblica.

Nota

Non è possibile omettere parametri durante la ricerca di costruttori e metodi. È possibile omettere i parametri solo quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con MethodInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i metodi del vincolo di classe o i metodi di se non è presente alcun vincolo di Object classe.

Nota

Per i metodi generici, non includere gli argomenti di tipo in name. Ad esempio, il codice GetMethod("MyMethod<int>") C# cerca un membro con il nome di testo "MyMethod<int>", anziché un metodo denominato MyMethod con un argomento generico di tipo int. Usare invece GetMethod("MyMethod") con il parametro appropriato nella types matrice.

Vedi anche

Si applica a