C# - GetMethod返回null

Gil*_*ams 12 c#

A上课了:

public abstract class A
{

}
Run Code Online (Sandbox Code Playgroud)

然后我有B一个源于它的课程:

public sealed class B : A
{
    public void SomeMethod()
    {
        var method = this.GetType().GetMethod("AddText");
    }

    private void AddText(string text)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么GetMethod返回null?

SLa*_*aks 18

默认情况下,Reflection仅搜索公共方法.

你需要通过BindingFlags.Instance | BindingFlags.NonPublic.


Rya*_*ann 16

var methodInfo = this.GetType().GetMethod("AddText", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null);
Run Code Online (Sandbox Code Playgroud)

您的方法有一个参数,您需要使用接受类型数组的重载作为参数类型和绑定标志.

在.net方法中,签名基于其名称,返回类型及其参数.

因此,如果您的方法有参数,您必须通过Type []告诉Reflection它具有哪些参数类型.