Type.GetMethod 메서드

정의

현재 Type의 특정 메서드를 가져옵니다.

오버로드

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

지정된 바인딩 제약 조건과 지정된 호출 규칙을 활용하여, 지정된 제네릭 매개 변수의 수, 인수 형식 및 한정자와 매개 변수가 일치하는 지정된 메서드를 검색합니다.

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

지정된 인수 형식 및 한정자와 일치하는 매개 변수를 가진 지정된 메서드를 지정된 바인딩 제약 조건과 지정된 호출 규칙으로 검색합니다.

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

지정된 바인딩 제약 조건을 사용하여, 지정된 제네릭 매개 변수의 수, 인수 형식 및 한정자와 매개 변수가 일치하는 지정된 메서드를 검색합니다.

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

지정된 인수 형식 및 한정자와 일치하는 매개 변수를 가진 지정된 메서드를 지정된 바인딩 제약 조건으로 검색합니다.

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

지정된 매개 변수의 수, 인수 형식 및 한정자와 매개 변수가 일치하는 지정된 공용 메서드를 검색합니다.

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

지정된 메서드를 지정된 바인딩 제약 조건으로 검색합니다.

GetMethod(String, BindingFlags, Type[])

지정된 바인딩 제약 조건을 사용하여 매개 변수가 지정된 인수 형식과 일치하는 지정된 메서드를 검색합니다.

GetMethod(String, Int32, Type[])

지정된 제네릭 매개 변수의 수 및 인수 형식과 매개 변수가 일치하는 지정된 공용 메서드를 검색합니다.

GetMethod(String, Type[])

지정된 인수 형식과 일치하는 매개 변수를 가진 지정된 public 메서드를 검색합니다.

GetMethod(String)

지정된 이름의 public 메서드를 검색합니다.

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

지정된 인수 형식 및 한정자와 일치하는 매개 변수를 가진 지정된 public 메서드를 검색합니다.

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

지정된 바인딩 제약 조건과 지정된 호출 규칙을 활용하여, 지정된 제네릭 매개 변수의 수, 인수 형식 및 한정자와 매개 변수가 일치하는 지정된 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

genericParameterCount
Int32

메서드의 제네릭 형식 매개 변수의 수입니다.

bindingAttr
BindingFlags

검색 방법을 지정하는 열거형 값의 비트 조합입니다.

또는

null을 반환하는 Default입니다.

binder
Binder

속성 집합을 정의하고 바인딩을 활성화하는 개체입니다. 이 개체는 또한 리플렉션을 통해 오버로드된 메서드를 선택할 수 있고 인수 형식을 강제 변환할 수 있으며 멤버를 호출할 수도 있습니다.

또는

Nothing를 사용하려면 null 참조(Visual Basic의 경우 DefaultBinder)입니다.

callConvention
CallingConventions

인수의 순서 및 레이아웃, 반환 값의 전달 방법, 인수에 사용되는 레지스터, 스택 정리 방법 등과 관련하여 사용할 규칙을 지정하는 개체입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

modifiers
ParameterModifier[]

ParameterModifier 배열에서 해당하는 요소와 연관된 특성을 나타내는 types 개체 배열입니다. COM interop를 통해 호출하는 경우에만 사용되며 참조에 의해 전달된 매개 변수만 처리합니다. 기본 바인더에서는 이 매개 변수를 처리하지 않습니다.

반환

(발견된 경우) 지정된 제네릭 매개 변수의 수, 인수 형식, 한정자, 바인딩 제약 조건 및 호출 규칙과 일치하는 메서드를 나타내는 개체입니다. 그 밖의 경우에는 null.

예외

namenull입니다.

또는

typesnull입니다.

또는

types 배열의 요소 중 하나가 null입니다.

genericParameterCount가 음수입니다.

적용 대상

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

지정된 인수 형식 및 한정자와 일치하는 매개 변수를 가진 지정된 메서드를 지정된 바인딩 제약 조건과 지정된 호출 규칙으로 검색합니다.

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

매개 변수

name
String

가져올 메서드의 이름이 포함된 문자열입니다.

bindingAttr
BindingFlags

검색 방법을 지정하는 열거형 값의 비트 조합입니다.

또는

null을 반환하는 Default입니다.

binder
Binder

속성 집합을 정의하고 바인딩을 활성화하는 개체입니다. 이 개체는 또한 리플렉션을 통해 오버로드된 메서드를 선택할 수 있고 인수 형식을 강제 변환할 수 있으며 멤버를 호출할 수도 있습니다.

또는

Nothing를 사용하려면 null 참조(Visual Basic의 경우 DefaultBinder)입니다.

callConvention
CallingConventions

인수의 순서 및 레이아웃, 반환 값의 전달 방법, 인수에 사용되는 레지스터, 스택 정리 방법 등과 관련하여 사용할 규칙을 지정하는 개체입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

modifiers
ParameterModifier[]

ParameterModifier 배열에서 해당하는 요소와 연관된 특성을 나타내는 types 개체 배열입니다. COM interop를 통해 호출하는 경우에만 사용되며 참조에 의해 전달된 매개 변수만 처리합니다. 기본 바인더에서는 이 매개 변수를 처리하지 않습니다.

반환

지정된 요구 사항과 일치하는 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

구현

예외

지정한 이름을 가지며 지정된 바인딩 제약 조건과 일치하는 메서드가 둘 이상 발견되었습니다.

name이(가) null인 경우

또는

typesnull입니다.

또는

types의 요소 중 하나가 null입니다.

types가 다차원 배열인 경우

또는

modifiers가 다차원 배열인 경우

예제

다음 예제에서는 바인딩 제약 조건, 호출 규칙 및 다양한 인수 형식을 지정하는 의 특정 오버로드 MethodA를 찾습니다.

참고

Visual C# 2005 예제에는 /unsafe 컴파일러 옵션이 필요합니다.

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

설명

기본 바인더는 (매개 변수)를 처리 ParameterModifier 하지 않지만 추상 System.Reflection.Binder 클래스를 사용하여 를 처리하는 modifiers사용자 지정 바인더를 작성할 수 modifiers 있습니다. ParameterModifier 는 COM interop을 통해 호출할 때만 사용되며 참조로 전달되는 매개 변수만 처리됩니다.

다음 표에서는 형식을 반영할 때 메서드에서 GetXXX 반환되는 기본 클래스의 멤버를 보여 줍니다.

멤버 형식 정적 비정적
생성자 아니요 아니요
필드 아니요 예. 필드는 항상 이름별 및 서명으로 숨겨집니다.
이벤트 해당 없음 일반적인 형식 시스템 규칙은 상속이 속성을 구현하는 메서드와 동일하다는 것입니다. 리플렉션은 속성을 이름별 숨기기 및 서명으로 처리합니다. 아래 참고 2를 참조하세요.
메서드 아니요 예. 메서드(가상 및 가상이 아닌 메서드)는 이름별 숨기기 또는 이름별 숨기기 및 서명일 수 있습니다.
중첩 형식 아니요 아니요
속성 해당 없음 일반적인 형식 시스템 규칙은 상속이 속성을 구현하는 메서드의 상속과 동일하다는 것입니다. 리플렉션은 속성을 hide-by-name-and-signature으로 처리합니다. 아래의 참고 2를 참조하세요.
  1. 이름별 숨기기 및 서명은 사용자 지정 한정자, 반환 형식, 매개 변수 형식, sentinels 및 관리되지 않는 호출 규칙을 포함하여 서명의 모든 부분을 고려합니다. 이진 비교입니다.

  2. 리플렉션의 경우 속성 및 이벤트는 이름별 숨기기 및 서명입니다. 기본 클래스에 get 및 set 접근자가 둘 다 있는 속성이 있지만 파생 클래스에 get 접근자만 있는 경우 파생 클래스 속성은 기본 클래스 속성을 숨기며 기본 클래스의 setter에 액세스할 수 없습니다.

  3. 사용자 지정 특성은 공통 형식 시스템의 일부가 아닙니다.

다음 BindingFlags 필터 플래그를 사용하여 검색에 포함할 메서드를 정의할 수 있습니다.

  • 반환을 얻으려면 또는 BindingFlags.Static 를 지정 BindingFlags.Instance 해야 합니다.

  • 검색에 공용 메서드를 포함하도록 지정 BindingFlags.Public 합니다.

  • 검색에 비공용 메서드(즉, 프라이빗, 내부 및 보호된 메서드)를 포함하도록 지정 BindingFlags.NonPublic 합니다.

  • 계층을 포함 public 하도록 지정 BindingFlags.FlattenHierarchy 하고 protected 정적 멤버를 지정합니다private. 상속된 클래스의 정적 멤버는 포함되지 않습니다.

다음 BindingFlags 한정자 플래그를 사용하여 검색 작동 방식을 변경할 수 있습니다.

  • BindingFlags.IgnoreCasename대/소문자를 무시합니다.

  • BindingFlags.DeclaredOnly 에 선언된 Type메서드만 검색하려면 이고, 단순히 상속된 메서드는 검색하지 않습니다.

자세한 내용은 System.Reflection.BindingFlags를 참조하세요.

참고

생성자 및 메서드를 조회할 때 매개 변수를 생략할 수 없습니다. 호출할 때만 매개 변수를 생략할 수 있습니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 를 반환 MethodInfo 합니다.

현재 Type 가 제네릭 형식 또는 제네릭 메서드의 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 메서드 또는 클래스 제약 조건이 없는 경우 의 Object 메서드를 검색합니다.

참고

제네릭 메서드의 경우 형식 인수를 에 name포함하지 마세요. 예를 들어 C# 코드 GetMember("MyMethod<int>") 는 형식int의 제네릭 인수가 하나 있는 라는 메서드가 아니라 텍스트 이름이 "MyMethod<int>"인 MyMethod 멤버를 검색합니다.

추가 정보

적용 대상

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

지정된 바인딩 제약 조건을 사용하여, 지정된 제네릭 매개 변수의 수, 인수 형식 및 한정자와 매개 변수가 일치하는 지정된 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

genericParameterCount
Int32

메서드의 제네릭 형식 매개 변수의 수입니다.

bindingAttr
BindingFlags

검색 방법을 지정하는 열거형 값의 비트 조합입니다.

또는

null을 반환하는 Default입니다.

binder
Binder

속성 집합을 정의하고 바인딩을 활성화하는 개체입니다. 이 개체는 또한 리플렉션을 통해 오버로드된 메서드를 선택할 수 있고 인수 형식을 강제 변환할 수 있으며 멤버를 호출할 수도 있습니다.

또는

Nothing를 사용하려면 null 참조(Visual Basic의 경우 DefaultBinder)입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

modifiers
ParameterModifier[]

ParameterModifier 배열에서 해당하는 요소와 연관된 특성을 나타내는 types 개체 배열입니다. COM interop를 통해 호출하는 경우에만 사용되며 참조에 의해 전달된 매개 변수만 처리합니다. 기본 바인더에서는 이 매개 변수를 처리하지 않습니다.

반환

(발견된 경우) 지정된 제네릭 매개 변수의 수, 인수 형식, 한정자 및 바인딩 제약 조건과 일치하는 메서드를 나타내는 개체입니다. 그 밖의 경우에는 null.

예외

namenull입니다.

또는

typesnull입니다.

또는

types 배열의 요소 중 하나가 null입니다.

genericParameterCount가 음수입니다.

적용 대상

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

지정된 인수 형식 및 한정자와 일치하는 매개 변수를 가진 지정된 메서드를 지정된 바인딩 제약 조건으로 검색합니다.

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

매개 변수

name
String

가져올 메서드의 이름이 포함된 문자열입니다.

bindingAttr
BindingFlags

검색 방법을 지정하는 열거형 값의 비트 조합입니다.

또는

null을 반환하는 Default입니다.

binder
Binder

속성 집합을 정의하고 바인딩을 활성화하는 개체입니다. 이 개체는 또한 리플렉션을 통해 오버로드된 메서드를 선택할 수 있고 인수 형식을 강제 변환할 수 있으며 멤버를 호출할 수도 있습니다.

또는

Nothing를 사용하려면 null 참조(Visual Basic의 경우 DefaultBinder)입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

modifiers
ParameterModifier[]

ParameterModifier 배열에서 해당하는 요소와 연관된 특성을 나타내는 types 개체 배열입니다. COM interop를 통해 호출하는 경우에만 사용되며 참조에 의해 전달된 매개 변수만 처리합니다. 기본 바인더에서는 이 매개 변수를 처리하지 않습니다.

반환

지정된 요구 사항과 일치하는 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

구현

예외

지정한 이름을 가지며 지정된 바인딩 제약 조건과 일치하는 메서드가 둘 이상 발견되었습니다.

name이(가) null인 경우

또는

typesnull입니다.

또는

types의 요소 중 하나가 null입니다.

types가 다차원 배열인 경우

또는

modifiers가 다차원 배열인 경우

예제

다음 예제에서는 바인딩 제약 조건 및 다양한 인수 형식을 지정하는 의 MethodA특정 오버로드를 찾습니다.

참고

Visual C# 2005 예제에는 /unsafe 컴파일러 옵션이 필요합니다.

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

설명

기본 바인더는 (modifiers매개 변수)를 처리하지 않지만 추상 System.Reflection.Binder 클래스를 사용하여 를 처리하는 ParameterModifiermodifiers사용자 지정 바인더를 작성할 수 있습니다. ParameterModifier 는 COM interop을 통해 호출할 때만 사용되며 참조로 전달되는 매개 변수만 처리됩니다.

다음 BindingFlags 필터 플래그를 사용하여 검색에 포함할 메서드를 정의할 수 있습니다.

  • 반환을 얻으려면 또는 BindingFlags.Static 를 지정 BindingFlags.Instance 해야 합니다.

  • 검색에 공용 메서드를 포함하도록 지정 BindingFlags.Public 합니다.

  • 검색에 비공용 메서드(즉, 프라이빗, 내부 및 보호된 메서드)를 포함하도록 지정 BindingFlags.NonPublic 합니다.

  • 계층을 포함 public 하도록 지정 BindingFlags.FlattenHierarchy 하고 protected 정적 멤버를 지정합니다private. 상속된 클래스의 정적 멤버는 포함되지 않습니다.

다음 BindingFlags 한정자 플래그를 사용하여 검색 작동 방식을 변경할 수 있습니다.

  • BindingFlags.IgnoreCasename대/소문자를 무시합니다.

  • BindingFlags.DeclaredOnly 에 선언된 Type메서드만 검색하려면 이고, 단순히 상속된 메서드는 검색하지 않습니다.

자세한 내용은 System.Reflection.BindingFlags를 참조하세요.

참고

생성자 및 메서드를 조회할 때 매개 변수를 생략할 수 없습니다. 호출할 때만 매개 변수를 생략할 수 있습니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 를 반환 MethodInfo 합니다.

현재 Type 가 제네릭 형식 또는 제네릭 메서드의 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 메서드 또는 클래스 제약 조건이 없는 경우 의 Object 메서드를 검색합니다.

참고

제네릭 메서드의 경우 형식 인수를 에 name포함하지 마세요. 예를 들어 C# 코드 GetMember("MyMethod<int>") 는 형식int의 제네릭 인수가 하나 있는 라는 메서드가 아니라 텍스트 이름이 "MyMethod<int>"인 MyMethod 멤버를 검색합니다.

추가 정보

적용 대상

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

지정된 매개 변수의 수, 인수 형식 및 한정자와 매개 변수가 일치하는 지정된 공용 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

genericParameterCount
Int32

메서드의 제네릭 형식 매개 변수의 수입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

modifiers
ParameterModifier[]

ParameterModifier 배열에서 해당하는 요소와 연관된 특성을 나타내는 types 개체 배열입니다. COM interop를 통해 호출하는 경우에만 사용되며 참조에 의해 전달된 매개 변수만 처리합니다. 기본 바인더에서는 이 매개 변수를 처리하지 않습니다.

반환

(발견된 경우) 지정된 제네릭 매개 변수의 수, 인수 형식 및 한정자와 일치하는 공용 메서드를 나타내는 개체입니다. 그 밖의 경우에는 null.

예외

namenull입니다.

또는

typesnull입니다.

또는

types 배열의 요소 중 하나가 null입니다.

genericParameterCount가 음수입니다.

적용 대상

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

매개 변수

name
String
genericParameterCount
Int32
bindingAttr
BindingFlags
types
Type[]

반환

적용 대상

GetMethod(String, BindingFlags)

지정된 메서드를 지정된 바인딩 제약 조건으로 검색합니다.

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

매개 변수

name
String

가져올 메서드의 이름이 포함된 문자열입니다.

bindingAttr
BindingFlags

검색 방법을 지정하는 열거형 값의 비트 조합입니다.

또는

null을 반환하는 Default입니다.

반환

지정된 요구 사항과 일치하는 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

구현

예외

지정한 이름을 가지며 지정된 바인딩 제약 조건과 일치하는 메서드가 둘 이상 발견되었습니다.

name이(가) null인 경우

예제

다음 예제에서는 지정된 바인딩 플래그와 일치하는 메서드를 가져옵니다.

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

설명

다음 BindingFlags 필터 플래그를 사용하여 검색에 포함할 메서드를 정의할 수 있습니다.

다음 BindingFlags 한정자 플래그를 사용하여 검색 작동 방식을 변경할 수 있습니다.

자세한 내용은 System.Reflection.BindingFlags를 참조하세요.

메서드가 오버로드되고 둘 이상의 오버로드가 인수로 bindingAttr 지정된 제약 조건을 충족하는 경우 메서드는 예외를 AmbiguousMatchException throw합니다. 다음 예제에서는 다음과 같은 이유로 예외가 throw됩니다.

  • 형식에는 TestClass 메서드 DisplayValue(String)DisplayValue(String, Object[])의 두 개의 공용 instance 오버로드가 DisplayValue 있습니다.

  • 형식에는 TestClass 메서드의 두 개의 공용 instance 오버로드가 Equals 있으며, 그 중 하나는 및 Equals(Object)에서 ObjectEquals(TestClass) 상속됩니다.

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)

다음 중 하나를 수행하여 특정 메서드를 검색할 수 있습니다.

  • 바인딩 제약 조건을 변경합니다. 이전 예제에서 형식으로 선언되고 상속되지 않은 공용 instance Equals 메서드를 검색하려고 시도하면 가 성공적으로 검색됩니다Equals(TestClass).

  • 메서드의 매개 변수 형식을 GetMethodtypes 정의하는 매개 변수를 포함하는 메서드의 오버로드를 호출합니다.

  • 메서드를 GetMethods(BindingFlags) 호출하여 지정된 바인딩 특성이 있는 형식에 속하는 모든 메서드를 포함하는 배열을 검색합니다. 그런 다음 반복하여 라는 name중복 메서드를 식별할 수 있습니다. 이 방법은 예외에 대한 이전 예제의 처리기에 설명되어 있습니다 AmbiguousMatchException .

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 를 반환 MethodInfo 합니다.

현재 Type 가 제네릭 형식 또는 제네릭 메서드의 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 메서드 또는 클래스 제약 조건이 없는 경우 의 Object 메서드를 검색합니다.

참고

제네릭 메서드의 경우 형식 인수를 에 name포함하지 마세요. 예를 들어 C# 코드 GetMember("MyMethod<int>") 는 형식int의 제네릭 인수가 하나 있는 라는 메서드가 아니라 텍스트 이름이 "MyMethod<int>"인 MyMethod 멤버를 검색합니다.

추가 정보

적용 대상

GetMethod(String, BindingFlags, Type[])

지정된 바인딩 제약 조건을 사용하여 매개 변수가 지정된 인수 형식과 일치하는 지정된 메서드를 검색합니다.

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

매개 변수

name
String

가져올 메서드의 이름이 포함된 문자열입니다.

bindingAttr
BindingFlags

검색 방법을 지정하는 열거형 값의 비트 조합입니다. -또는- 를 반환 null하는 기본값입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다. -또는- 매개 변수를 사용하지 않는 메서드를 가져오는 빈 개체 배열 Type (필드에서 제공 EmptyTypes )입니다.

반환

지정된 요구 사항과 일치하는 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

적용 대상

GetMethod(String, Int32, Type[])

지정된 제네릭 매개 변수의 수 및 인수 형식과 매개 변수가 일치하는 지정된 공용 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

genericParameterCount
Int32

메서드의 제네릭 형식 매개 변수의 수입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

반환

(발견된 경우) 지정 제네릭 매개 변수의 수 및 인수 형식과 매개 변수가 일치하는 공용 메서드를 나타내는 개체입니다. 그 밖의 경우에는 null.

예외

namenull입니다.

또는

typesnull입니다.

또는

types 배열의 요소 중 하나가 null입니다.

genericParameterCount가 음수입니다.

적용 대상

GetMethod(String, Type[])

지정된 인수 형식과 일치하는 매개 변수를 가진 지정된 public 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

반환

지정된 인수 형식과 일치하는 매개 변수를 가진 public 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

구현

예외

지정된 이름 및 지정된 매개 변수를 사용하는 메서드가 두 개 이상입니다.

name이(가) null인 경우

또는

typesnull입니다.

또는

types의 요소 중 하나가 null입니다.

types가 다차원 배열인 경우

예제

다음 예제에서는 다양한 인수 형식을 지정하는 의 MethodA특정 오버로드를 찾습니다.

참고

Visual C# 2005 예제에는 /unsafe 컴파일러 옵션이 필요합니다.

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

다음 예제에서는 제네릭이 아닌 형식(클래스), 열린 제네릭 형식(ArrayList클래스) 및 닫힌 제네릭 형식(List<T>형식)List(Of String)의 메서드를 나타내는 Add 개체를 검색 MethodInfo 합니다.

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)

이 예제에서는 적절한 MethodInfo 개체를 GetAddMethod 검색하는 메서드를 정의합니다. 열려 있는 types 제네릭 형식에 대한 인수를 제공하기 위해 메서드를 호출합니다 Type.GetGenericArguments . 닫힌 types 제네릭 형식에 대한 인수를 제공하기 위해 속성 값을 Type.GenericTypeArguments 검색합니다.

설명

에 대한 name 검색은 대/소문자를 구분합니다. 검색에는 공용 정적 및 공용 instance 메서드가 포함됩니다.

참고

생성자 및 메서드를 조회할 때 매개 변수를 생략할 수 없습니다. 호출할 때만 매개 변수를 생략할 수 있습니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 를 반환 MethodInfo 합니다.

현재 Type 가 제네릭 형식 또는 제네릭 메서드의 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 메서드 또는 클래스 제약 조건이 없는 경우 의 Object 메서드를 검색합니다.

참고

매개 변수에는 name 형식 인수를 포함할 수 없습니다. 예를 들어 C# 코드 GetMethod("MyGenericMethod<int>") 는 형식int의 제네릭 인수가 하나 있는 라는 메서드가 아니라 텍스트 이름이 "MyGenericMethod<int>"인 MyGenericMethod 메서드를 검색합니다. 대신 배열에서 적절한 매개 변수와 함께 를 types 사용합니다GetMethod("MyGenericMethod").

추가 정보

적용 대상

GetMethod(String)

지정된 이름의 public 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

반환

지정된 이름의 public 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

구현

예외

지정한 이름을 가진 메서드가 둘 이상 있습니다.

name이(가) null인 경우

예제

다음 예제에서는 라는 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

설명

검색 name 은 대/소문자를 구분합니다. 검색에는 공용 정적 및 공용 instance 메서드가 포함됩니다.

메서드가 오버로드되고 둘 이상의 공용 메서드가 있는 경우 메서드는 GetMethod(String) 예외를 AmbiguousMatchException throw합니다. 다음 예제에서는 메서드의 공용 오버로드가 둘 이상 있으므로 예외가 Int32.ToString throw됩니다. 반면에 메서드가 재정 Object.ToStringPerson.ToString 되어 오버로드되지 GetMethod(String) 않으므로 메서드는 개체를 검색 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.

다음 중 하나를 수행하여 특정 메서드를 검색할 수 있습니다.

  • 메서드를 GetMethod(String, BindingFlags) 호출하고 메서드를 bindingAttr 고유하게 식별하는 인수를 지정합니다. 예를 들어 형식에 정적 및 instance 오버로드가 있으므로 예외가 throw되는 경우 의 BindingFlags.InstanceOrBindingFlags.Instance인수를 bindingAttr 지정할 수 있습니다.

  • 메서드의 매개 변수 형식을 GetMethod 정의하는 매개 변수를 포함하는 types 메서드의 오버로드를 호출합니다.

  • 메서드를 GetMethods() 호출하여 형식에 속하는 모든 공용 메서드가 포함된 배열을 검색합니다. 그런 다음 반복하여 라는 name중복 메서드를 식별할 수 있습니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 를 반환 MethodInfo 합니다.

현재 Type 가 제네릭 형식 또는 제네릭 메서드의 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 메서드 또는 클래스 제약 조건이 없는 경우 의 메서드를 Object 검색합니다.

참고

제네릭 메서드의 경우 형식 인수를 에 name포함하지 마세요. 예를 들어 C# 코드 GetMember("MyMethod<int>") 는 형식int의 제네릭 인수가 하나 있는 메서드가 아닌 텍스트 이름이 "MyMethod<int>"인 MyMethod 멤버를 검색합니다.

추가 정보

적용 대상

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

지정된 인수 형식 및 한정자와 일치하는 매개 변수를 가진 지정된 public 메서드를 검색합니다.

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

매개 변수

name
String

가져올 public 메서드의 이름이 포함된 문자열입니다.

types
Type[]

가져올 메서드에 대한 매개 변수의 수, 차수, 형식 등을 나타내는 Type 개체 배열입니다.

또는

매개 변수를 사용하지 않는 메서드를 가져올 Type 개체(EmptyTypes 필드에서 제공됨)의 빈 배열입니다.

modifiers
ParameterModifier[]

ParameterModifier 배열에서 해당하는 요소와 연관된 특성을 나타내는 types 개체 배열입니다. COM interop를 통해 호출하는 경우에만 사용되며 참조에 의해 전달된 매개 변수만 처리합니다. 기본 바인더에서는 이 매개 변수를 처리하지 않습니다.

반환

지정된 요구 사항과 일치하는 public 메서드를 나타내는 개체이며(있는 경우), 이러한 개체가 없으면 null을 반환합니다.

구현

예외

지정된 이름 및 지정된 매개 변수를 사용하는 메서드가 두 개 이상입니다.

name이(가) null인 경우

또는

typesnull입니다.

또는

types의 요소 중 하나가 null입니다.

types가 다차원 배열인 경우

또는

modifiers가 다차원 배열인 경우

설명

기본 바인더는 (매개 변수)를 처리 ParameterModifier 하지 않지만 추상 System.Reflection.Binder 클래스를 사용하여 를 처리하는 modifiers사용자 지정 바인더를 작성할 수 modifiers 있습니다. ParameterModifier 는 COM interop을 통해 호출할 때만 사용되며 참조로 전달되는 매개 변수만 처리됩니다.

검색 name 은 대/소문자를 구분합니다. 검색에는 공용 정적 및 공용 instance 메서드가 포함됩니다.

참고

생성자 및 메서드를 조회할 때 매개 변수를 생략할 수 없습니다. 호출할 때만 매개 변수를 생략할 수 있습니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 를 반환 MethodInfo 합니다.

현재 Type 가 제네릭 형식 또는 제네릭 메서드의 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 메서드 또는 클래스 제약 조건이 없는 경우 의 메서드를 Object 검색합니다.

참고

제네릭 메서드의 경우 형식 인수를 에 name포함하지 마세요. 예를 들어 C# 코드 GetMethod("MyMethod<int>") 는 형식int의 제네릭 인수가 하나 있는 메서드가 아닌 텍스트 이름이 "MyMethod<int>"인 MyMethod 멤버를 검색합니다. 대신 배열에서 적절한 매개 변수와 함께 를 types 사용합니다GetMethod("MyMethod").

추가 정보

적용 대상