2024年4月20日发(作者:)

在.NET Core中,您可以使用反射来获取MethodInfo对象,它表示类的方法的元数据。以

下是几种获取MethodInfo的常用方法:

使用Type类的GetMethod方法

如果您知道方法的名字和参数类型,您可以使用Type类的GetMethod方法来获取

MethodInfo。

csharp

using System;

using tion;

public class MyClass

{

public void MyMethod(int value)

{

ine(value);

}

}

class Program

{

static void Main()

{

Type myType = typeof(MyClass);

MethodInfo methodInfo = hod("MyMethod", new Type[]

{ typeof(int) });

if (methodInfo != null)

{

ine("Method found: " + );

}

}

}

在上面的代码中,我们有一个名为MyClass的类,其中包含一个名为MyMethod的方法。在

Main方法中,我们使用GetMethod来检索表示该方法的MethodInfo对象。我们传递了方法

名和一个包含参数类型的Type数组给GetMethod。

使用Type类的GetMethods方法

如果您想获取类中定义的所有方法,而不只是特定的一个,您可以使用GetMethods方法,

它返回一个MethodInfo对象的数组。

csharp

using System;

using tion;

public class MyClass

{

public void MyMethod1() { }

public void MyMethod2() { }

}

class Program

{

static void Main()

{

Type myType = typeof(MyClass);

MethodInfo[] methods = hods();

foreach (MethodInfo method in methods)

{

ine("Method: " + );

}

}

}

在上面的代码中,我们定义了一个包含两个方法的类。在Main方法中,我们使用GetMethods

来检索一个包含类中所有公共方法的数组,并遍历它们以打印每个方法的名称。

使用BindingFlags枚举

在获取方法时,您可能想更精细地控制检索的范围,例如是否包括非公共方法或静态方法等。

在这种情况下,您可以使用BindingFlags枚举与GetMethod或GetMethods方法一起使用。

csharp

using System;

using tion;

public class MyClass

{

private static void MyPrivateStaticMethod() { }

}

class Program

{

static void Main()

{

Type myType = typeof(MyClass);

MethodInfo methodInfo = hod("MyPrivateStaticMethod",

lic | );

if (methodInfo != null)

{

ine("Method found: " + );

}

}

}