Type.GetMethod Type.GetMethod Type.GetMethod Type.GetMethod Method

定义

获取当前 Type 的特定方法。Gets a specific method of the current Type.

重载

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

用指定的绑定约束和指定的调用约定,搜索参数与指定的参数类型及修饰符相匹配的指定方法。Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

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

使用指定绑定约束,搜索其参数与指定参数类型及修饰符匹配的指定方法。Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.

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

搜索其参数与指定参数类型匹配的指定公共方法。Searches for the specified public method whose parameters match the specified argument types.

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

使用指定绑定约束搜索指定方法。Searches for the specified method, using the specified binding constraints.

GetMethod(String) GetMethod(String) GetMethod(String) GetMethod(String)

搜索具有指定名称的公共方法。Searches for the public method with the specified name.

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

搜索其参数与指定参数类型及修饰符匹配的指定公共方法。Searches for the specified public method whose parameters match the specified argument types and modifiers.

GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) 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);
member this.GetMethod : string * int * System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo

参数

genericParameterCount
Int32 Int32 Int32 Int32
types
Type[]
modifiers
ParameterModifier[]

返回

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

用指定的绑定约束和指定的调用约定,搜索参数与指定的参数类型及修饰符相匹配的指定方法。Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

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

参数

name
String String String String

包含要获取的方法名称的字符串。The string containing the name of the method to get.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted.

- 或 --or- 若为 Default,则返回 nullDefault to return null.

binder
Binder Binder Binder Binder

一个对象,该对象定义一组属性并启用绑定,而绑定可能涉及选择重载方法、强制参数类型和通过反射调用成员。An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

- 或 --or- 要使用 Nothing 的空引用(在 Visual Basic 中为 DefaultBinder)。A null reference (Nothing in Visual Basic), to use the DefaultBinder.

callConvention
CallingConventions CallingConventions CallingConventions CallingConventions

该对象用于指定要使用的一套规则,这些规则涉及自变量的顺序和布局、传递返回值的方式、用于自变量的寄存器和清理堆栈的方式。The object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and how the stack is cleaned up.

types
Type[]

表示此方法要获取的参数的个数、顺序和类型的 Type 对象数组。An array of Type objects representing the number, order, and type of the parameters for the method to get.

- 或 --or- 空的 Type 对象数组(由 EmptyTypes 字段提供),用来获取不采用参数的方法。An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

ParameterModifier 对象的数组,表示与 types 数组中的相应元素关联的特性。An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. 仅当通过 COM 互操作进行调用时才使用,而且仅处理通过引用传递的参数。To be only used when calling through COM interop, and only parameters that are passed by reference are handled. 默认的联编程序不处理此参数。The default binder does not process this parameter.

返回

表示符合指定要求的方法的对象(如果找到的话);否则为 nullAn object representing the method that matches the specified requirements, if found; otherwise, null.

实现

异常

找到多个具有指定名称且与指定绑定约束匹配的方法。More than one method is found with the specified name and matching the specified binding constraints.

namenullname is null.

-or- typesnulltypes is null.

- 或 --or- types 的其中一个元素为 nullOne of the elements in types is null.

types 是多维的。types is multidimensional.

- 或 --or- modifiers 是多维的。modifiers is multidimensional.

示例

下面的示例查找的特定重载MethodA,指定绑定约束,调用约定和不同的参数类型。The following example finds specific overloads of MethodA, specifying binding constraints, calling conventions, and a variety of argument types.

备注

Visual C# 2005Visual C# 2005示例需要/unsafe编译器选项。The Visual C# 2005Visual C# 2005 example requires the /unsafe compiler option.

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 Program
{
    // 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);

  }
}

Imports System
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(modifiers参数),您可以使用抽象System.Reflection.Binder类以编写的自定义联编程序modifiersAlthough the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier 通过 COM 互操作调用时,才使用和处理由引用传递的参数。ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

下表显示了返回通过基类的成员GetXXX方法反射的类型上时。The following table shows what members of a base class are returned by the GetXXX methods when reflecting on a type.

成员类型Member Type StaticStatic 非静态Non-Static
构造函数Constructor NoNo NoNo
字段Field NoNo 可以。Yes. 字段始终是按名称和签名隐藏。A field is always hide-by-name-and-signature.
事件Event 不适用Not applicable 通用类型系统规则是继承是实现的属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为由名称和签名隐藏。Reflection treats properties as hide-by-name-and-signature. 请参阅备注 2 下面。See note 2 below.
方法Method NoNo 可以。Yes. 方法 (包括虚拟和非虚拟) 可以隐藏通过名称或按名称和签名隐藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
嵌套的类型Nested Type NoNo NoNo
PropertyProperty 不适用Not applicable 通用类型系统规则是继承是实现的属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为由名称和签名隐藏。Reflection treats properties as hide-by-name-and-signature. 请参阅备注 2 下面。See note 2 below.
  1. 按名称和签名隐藏会考虑所有的签名,包括自定义修饰符,部分返回类型、 参数类型、 标记和非托管调用约定。Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. 这是二进制比较。This is a binary comparison.

  2. 为反射,属性和事件均由名称和签名隐藏。For reflection, properties and events are hide-by-name-and-signature. 如果具有 get 和 set 访问器的属性中的基类,但派生的类具有一个 get 访问器,派生的类属性隐藏基类属性,并且你将无法再访问基类上的资源库。If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. 自定义特性不是通用类型系统的一部分。Custom attributes are not part of the common type system.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的方法:The following BindingFlags filter flags can be used to define which methods to include in the search:

  • 您必须指定这两BindingFlags.InstanceBindingFlags.Static为了获取返回。You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • 指定BindingFlags.Public若要在搜索中包括公共方法。Specify BindingFlags.Public to include public methods in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共方法 (即私有、 内部和受保护方法)。Specify BindingFlags.NonPublic to include nonpublic methods (that is, private, internal, and protected methods) in the search.

  • 指定BindingFlags.FlattenHierarchy用以publicprotected层次结构; 上的静态成员private中继承的类的静态成员不包括。Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索仅上声明的方法Type,不只是继承的方法。BindingFlags.DeclaredOnly to search only the methods declared on the Type, not methods that were simply inherited.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

备注

查找构造函数和方法时,不能省略参数。You cannot omit parameters when looking up constructors and methods. 调用时,仅可以省略参数。You can only omit parameters when invoking.

如果当前Type表示构造泛型类型,此方法返回MethodInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法,则此方法的定义中的类型参数搜索类约束的方法或方法的Object如果没有类约束。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

备注

为泛型方法,不包括中的类型参数nameFor generic methods, do not include the type arguments in name. 例如,C# 代码GetMember("MyMethod<int>")搜索的文本名称的成员"MyMethod<int>",而不是针对一个名为方法MyMethod具有一个类型的泛型参数intFor example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

另请参阅

GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[]) GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[]) 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);
member this.GetMethod : string * int * System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.MethodInfo

参数

genericParameterCount
Int32 Int32 Int32 Int32
types
Type[]
modifiers
ParameterModifier[]

返回

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

使用指定绑定约束,搜索其参数与指定参数类型及修饰符匹配的指定方法。Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.

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

参数

name
String String String String

包含要获取的方法名称的字符串。The string containing the name of the method to get.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted.

- 或 --or- 若为 Default,则返回 nullDefault to return null.

binder
Binder Binder Binder Binder

一个对象,该对象定义一组属性并启用绑定,而绑定可能涉及选择重载方法、强制参数类型和通过反射调用成员。An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

- 或 --or- 要使用 Nothing 的空引用(在 Visual Basic 中为 DefaultBinder)。A null reference (Nothing in Visual Basic), to use the DefaultBinder.

types
Type[]

表示此方法要获取的参数的个数、顺序和类型的 Type 对象数组。An array of Type objects representing the number, order, and type of the parameters for the method to get.

- 或 --or- 空的 Type 对象数组(由 EmptyTypes 字段提供),用来获取不采用参数的方法。An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

ParameterModifier 对象的数组,表示与 types 数组中的相应元素关联的特性。An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. 仅当通过 COM 互操作进行调用时才使用,而且仅处理通过引用传递的参数。To be only used when calling through COM interop, and only parameters that are passed by reference are handled. 默认的联编程序不处理此参数。The default binder does not process this parameter.

返回

表示符合指定要求的方法的对象(如果找到的话);否则为 nullAn object representing the method that matches the specified requirements, if found; otherwise, null.

实现

异常

找到多个具有指定名称且与指定绑定约束匹配的方法。More than one method is found with the specified name and matching the specified binding constraints.

namenullname is null.

-or- typesnulltypes is null.

- 或 --or- types 的其中一个元素为 nullOne of the elements in types is null.

types 是多维的。types is multidimensional.

- 或 --or- modifiers 是多维的。modifiers is multidimensional.

示例

下面的示例查找的特定重载MethodA,指定绑定约束和不同的参数类型。The following example finds specific overloads of MethodA, specifying binding constraints and a variety of argument types.

备注

Visual C# 2005Visual C# 2005示例需要/unsafe编译器选项。The Visual C# 2005Visual C# 2005 example requires the /unsafe compiler option.

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 Program
{
    // 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);

  }
}

Imports System
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

注解

尽管默认联编程序不会处理ParameterModifier(modifiers参数),您可以使用抽象System.Reflection.Binder类以编写的自定义联编程序modifiersAlthough the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier 通过 COM 互操作调用时,才使用和处理由引用传递的参数。ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的方法:The following BindingFlags filter flags can be used to define which methods to include in the search:

  • 您必须指定这两BindingFlags.InstanceBindingFlags.Static为了获取返回。You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • 指定BindingFlags.Public若要在搜索中包括公共方法。Specify BindingFlags.Public to include public methods in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共方法 (即私有、 内部和受保护方法)。Specify BindingFlags.NonPublic to include nonpublic methods (that is, private, internal, and protected methods) in the search.

  • 指定BindingFlags.FlattenHierarchy用以publicprotected层次结构; 上的静态成员private中继承的类的静态成员不包括。Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索仅上声明的方法Type,不只是继承的方法。BindingFlags.DeclaredOnly to search only the methods declared on the Type, not methods that were simply inherited.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

备注

查找构造函数和方法时,不能省略参数。You cannot omit parameters when looking up constructors and methods. 调用时,仅可以省略参数。You can only omit parameters when invoking.

如果当前Type表示构造泛型类型,此方法返回MethodInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法,则此方法的定义中的类型参数搜索类约束的方法或方法的Object如果没有类约束。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

备注

为泛型方法,不包括中的类型参数nameFor generic methods, do not include the type arguments in name. 例如,C# 代码GetMember("MyMethod<int>")搜索的文本名称的成员"MyMethod<int>",而不是针对一个名为方法MyMethod具有一个类型的泛型参数intFor example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

另请参阅

GetMethod(String, Int32, Type[], ParameterModifier[]) GetMethod(String, Int32, Type[], ParameterModifier[]) GetMethod(String, Int32, Type[], ParameterModifier[]) 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);
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

参数

genericParameterCount
Int32 Int32 Int32 Int32
types
Type[]
modifiers
ParameterModifier[]

返回

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

搜索其参数与指定参数类型匹配的指定公共方法。Searches for the specified public method whose parameters match the specified argument types.

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

包含要获取的公共方法的名称的字符串。The string containing the name of the public method to get.

types
Type[]

表示此方法要获取的参数的个数、顺序和类型的 Type 对象数组。An array of Type objects representing the number, order, and type of the parameters for the method to get.

- 或 --or- 空的 Type 对象数组(由 EmptyTypes 字段提供),用来获取不采用参数的方法。An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

返回

表示其参数与指定参数类型匹配的公共方法的对象(如果找到的话);否则为 nullAn object representing the public method whose parameters match the specified argument types, if found; otherwise, null.

实现

异常

找到了多个具有指定名称和指定参数的方法。More than one method is found with the specified name and specified parameters.

namenullname is null.

-or- typesnulltypes is null.

- 或 --or- types 的其中一个元素为 nullOne of the elements in types is null.

types 是多维的。types is multidimensional.

示例

下面的示例查找的特定重载MethodA,指定不同的参数类型。The following example finds specific overloads of MethodA, specifying a variety of argument types.

备注

Visual C# 2005Visual C# 2005示例需要/unsafe编译器选项。The Visual C# 2005Visual C# 2005 example requires the /unsafe compiler option.

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 Program
{
    // 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);

  }
}

Imports System
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

下面的示例检索MethodInfo这些对象表示Add非泛型类型的方法 (ArrayList类),开放式泛型类型 (List<T>类),并已关闭的泛型类型 (List(Of String)类型。The following example retrieves MethodInfo objects that represent the Add methods of a non-generic type (the ArrayList class), an open generic type (the List<T> class), and a closed generic type (the List(Of String) type.

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

该示例定义了GetAddMethod检索相应的方法MethodInfo对象。The example defines a GetAddMethod method that retrieves the appropriate MethodInfo object. 若要提供types开放式泛型类型参数,它将调用Type.GetGenericArguments方法。To provide the types argument for an open generic type, it calls the Type.GetGenericArguments method. 若要提供types封闭式泛型类型参数,它检索的值Type.GenericTypeArguments属性。To provide the types argument for a closed generic type, it retrieves the value of the Type.GenericTypeArguments property.

注解

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括的公共静态和公共实例方法。The search includes public static and public instance methods.

备注

查找构造函数和方法时,不能省略参数。You cannot omit parameters when looking up constructors and methods. 调用时,仅可以省略参数。You can only omit parameters when invoking.

如果当前Type表示构造泛型类型,此方法返回MethodInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法,则此方法的定义中的类型参数搜索类约束的方法或方法的Object如果没有类约束。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

备注

name参数不能包含类型参数。The name parameter cannot include type arguments. 例如,C# 代码GetMethod("MyGenericMethod<int>")搜索的文本名称与方法"MyGenericMethod<int>",而不是针对一个名为方法MyGenericMethod具有一个类型的泛型参数intFor example, the C# code GetMethod("MyGenericMethod<int>") searches for a method with the text name "MyGenericMethod<int>", rather than for a method named MyGenericMethod that has one generic argument of type int. 请改用GetMethod("MyGenericMethod")中的相应参数与types数组。Instead, use GetMethod("MyGenericMethod") with the appropriate parameter in the types array.

另请参阅

GetMethod(String, Int32, Type[]) GetMethod(String, Int32, Type[]) GetMethod(String, Int32, Type[]) 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);
member this.GetMethod : string * int * Type[] -> System.Reflection.MethodInfo
Public Function GetMethod (name As String, genericParameterCount As Integer, types As Type()) As MethodInfo

参数

genericParameterCount
Int32 Int32 Int32 Int32
types
Type[]

返回

GetMethod(String, BindingFlags) GetMethod(String, BindingFlags) GetMethod(String, BindingFlags) GetMethod(String, BindingFlags)

使用指定绑定约束搜索指定方法。Searches for the specified method, using the specified binding constraints.

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

包含要获取的方法名称的字符串。The string containing the name of the method to get.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted.

- 或 --or- 若为 Default,则返回 nullDefault to return null.

返回

表示符合指定要求的方法的对象(如果找到的话);否则为 nullAn object representing the method that matches the specified requirements, if found; otherwise, null.

实现

异常

找到多个具有指定名称且与指定绑定约束匹配的方法。More than one method is found with the specified name and matching the specified binding constraints.

示例

下面的示例获取与指定的绑定标志匹配的方法。The following example gets the method that matches the specified binding flags.

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 Program
{

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

    }
}

Imports System
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的筛选器标志可以用于定义要在搜索中包括的方法:The following BindingFlags filter flags can be used to define which methods to include in the search:

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果一种方法重载方法,多个重载满足指定的约束bindingAttr参数,该方法将引发AmbiguousMatchException异常。If a method is overloaded and more than one overload meets the constraints specified by the bindingAttr argument, the method throws an AmbiguousMatchException exception. 在以下示例中,因为引发异常:In the following example, an exception is thrown because:

  • TestClass类型具有两个公共实例重载DisplayValue方法,DisplayValue(String)DisplayValue(String, Object[])The TestClass type has two public instance overloads of the DisplayValue method, DisplayValue(String) and DisplayValue(String, Object[]).

  • TestClass类型具有两个公共实例重载Equals方法,其中之一继承自Object:Equals(TestClass)Equals(Object)The TestClass type has two public instance overloads of the Equals method, one of which is inherited from Object: Equals(TestClass) and 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 Example
{
   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)
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)

可以执行以下操作以检索特定的方法之一:You can do one of the following to retrieve a specific method:

  • 更改的绑定约束。Change the binding constraints. 在上一示例中,尝试检索公共实例Equals方法,它是由类型声明并不继承已成功检索Equals(TestClass)In the previous example, attempting to retrieve a public instance Equals method that is declared by the type and not inherited successfully retrieves Equals(TestClass).

  • 调用重载GetMethod方法,包括types定义的方法的参数类型的参数。Call an overload of the GetMethod method that includes a types parameter which defines the types of the method's parameters.

  • 调用GetMethods(BindingFlags)方法来检索包含所有具有指定的绑定属性的方法属于一种类型的数组。Call the GetMethods(BindingFlags) method to retrieve an array containing all of the methods belonging to a type that have the specified binding attributes. 然后可以循环访问来识别重复的方法名为nameYou can then iterate it to identify the duplicate methods named name. 这种方法上一示例的处理程序中所示AmbiguousMatchException异常。This approach is illustrated in the previous example's handler for the AmbiguousMatchException exception.

如果当前Type表示构造泛型类型,此方法返回MethodInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法,则此方法的定义中的类型参数搜索类约束的方法或方法的Object如果没有类约束。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

备注

为泛型方法,不包括中的类型参数nameFor generic methods, do not include the type arguments in name. 例如,C# 代码GetMember("MyMethod<int>")搜索的文本名称的成员"MyMethod<int>",而不是针对一个名为方法MyMethod具有一个类型的泛型参数intFor example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

另请参阅

GetMethod(String) GetMethod(String) GetMethod(String) GetMethod(String)

搜索具有指定名称的公共方法。Searches for the public method with the specified name.

public:
 virtual System::Reflection::MethodInfo ^ GetMethod(System::String ^ name);
public System.Reflection.MethodInfo GetMethod (string name);
abstract member GetMethod : string -> System.Reflection.MethodInfo
override this.GetMethod : string -> System.Reflection.MethodInfo
Public Function GetMethod (name As String) As MethodInfo

参数

name
String String String String

包含要获取的公共方法的名称的字符串。The string containing the name of the public method to get.

返回

表示具有指定名称的公共方法的对象(如果找到的话);否则为 nullAn object that represents the public method with the specified name, if found; otherwise, null.

实现

异常

找到了多个具有指定名称的方法。More than one method is found with the specified name.

示例

下面的示例获取名为的方法MethodAThe following example gets a method named 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);

    }
}

Imports System
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区分大小写。The search for name is case-sensitive. 搜索中包括的公共静态和公共实例方法。The search includes public static and public instance methods.

如果一种方法重载方法,有多个公共方法GetMethod(String)方法会抛出AmbiguousMatchException异常。If a method is overloaded and has more than one public method, the GetMethod(String) method throws an AmbiguousMatchException exception. 在以下示例中,将引发异常的多个公共重载是Int32.ToString方法。In the following example, an exception is thrown because there is more than one public overload of the Int32.ToString method. 但是,由于Person.ToString方法重写Object.ToString,因此未重载,则GetMethod(String)方法是可以检索MethodInfo对象。On the other hand, because the Person.ToString method overrides Object.ToString and therefore is not overloaded, the GetMethod(String) method is able to retrieve the MethodInfo object.

using System;
using System.Reflection;

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

public class Example
{
   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.
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.

可以执行以下操作以检索特定的方法之一:You can do one of the following to retrieve a specific method:

  • 调用GetMethod(String, BindingFlags)方法并指定bindingAttr唯一标识该方法的参数。Call the GetMethod(String, BindingFlags) method and specify a bindingAttr argument that uniquely identifies the method. 例如,如果将引发异常,因为类型具有一个静态和实例重载,则可以指定bindingAttr的参数BindingFlags.Instance Or BindingFlags.InstanceFor example, if the exception is thrown because a type has a static and an instance overload, you can specify a bindingAttr argument of BindingFlags.InstanceOrBindingFlags.Instance.

  • 调用重载GetMethod方法,包括types定义的方法的参数类型的参数。Call an overload of the GetMethod method that includes a types parameter which defines the types of the method's parameters.

  • 调用GetMethods()方法来检索包含所有属于一种类型的公共方法的数组。Call the GetMethods() method to retrieve an array containing all of the public methods belonging to a type. 然后可以循环访问来识别重复的方法名为nameYou can then iterate it to identify the duplicate methods named name.

如果当前Type表示构造泛型类型,此方法返回MethodInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法,则此方法的定义中的类型参数搜索类约束的方法或方法的Object如果没有类约束。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

备注

为泛型方法,不包括中的类型参数nameFor generic methods, do not include the type arguments in name. 例如,C# 代码GetMember("MyMethod<int>")搜索的文本名称的成员"MyMethod<int>",而不是针对一个名为方法MyMethod具有一个类型的泛型参数intFor example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

另请参阅

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

搜索其参数与指定参数类型及修饰符匹配的指定公共方法。Searches for the specified public method whose parameters match the specified argument types and 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);
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 String String String

包含要获取的公共方法的名称的字符串。The string containing the name of the public method to get.

types
Type[]

表示此方法要获取的参数的个数、顺序和类型的 Type 对象数组。An array of Type objects representing the number, order, and type of the parameters for the method to get.

- 或 --or- 空的 Type 对象数组(由 EmptyTypes 字段提供),用来获取不采用参数的方法。An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

ParameterModifier 对象的数组,表示与 types 数组中的相应元素关联的特性。An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. 仅当通过 COM 互操作进行调用时才使用,而且仅处理通过引用传递的参数。To be only used when calling through COM interop, and only parameters that are passed by reference are handled. 默认的联编程序不处理此参数。The default binder does not process this parameter.

返回

表示符合指定要求的公共方法的对象(如果找到的话);否则为 nullAn object representing the public method that matches the specified requirements, if found; otherwise, null.

实现

异常

找到了多个具有指定名称和指定参数的方法。More than one method is found with the specified name and specified parameters.

namenullname is null.

-or- typesnulltypes is null.

- 或 --or- types 的其中一个元素为 nullOne of the elements in types is null.

types 是多维的。types is multidimensional.

- 或 --or- modifiers 是多维的。modifiers is multidimensional.

注解

尽管默认联编程序不会处理ParameterModifier(modifiers参数),您可以使用抽象System.Reflection.Binder类以编写的自定义联编程序modifiersAlthough the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier 通过 COM 互操作调用时,才使用和处理由引用传递的参数。ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括的公共静态和公共实例方法。The search includes public static and public instance methods.

备注

查找构造函数和方法时,不能省略参数。You cannot omit parameters when looking up constructors and methods. 调用时,仅可以省略参数。You can only omit parameters when invoking.

如果当前Type表示构造泛型类型,此方法返回MethodInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法,则此方法的定义中的类型参数搜索类约束的方法或方法的Object如果没有类约束。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

备注

为泛型方法,不包括中的类型参数nameFor generic methods, do not include the type arguments in name. 例如,C# 代码GetMethod("MyMethod<int>")搜索的文本名称的成员"MyMethod<int>",而不是针对一个名为方法MyMethod具有一个类型的泛型参数intFor example, the C# code GetMethod("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int. 请改用GetMethod("MyMethod")中的相应参数与types数组。Instead, use GetMethod("MyMethod") with the appropriate parameter in the types array.

另请参阅

适用于