[英]C# - GetMethod returns null
I have A
class: 我有
A
节课:
public abstract class A
{
}
And then I have B
class that derives from it: 然后我有
B
类派生自它:
public sealed class B : A
{
public void SomeMethod()
{
var method = this.GetType().GetMethod("AddText");
}
private void AddText(string text)
{
...
}
}
Why is GetMethod
returning null? 为什么
GetMethod
返回null?
By default, Reflection will only search for public methods. 默认情况下,Reflection只搜索公共方法。
You need to pass BindingFlags.Instance | BindingFlags.NonPublic
你需要传递
BindingFlags.Instance | BindingFlags.NonPublic
BindingFlags.Instance | BindingFlags.NonPublic
. BindingFlags.Instance | BindingFlags.NonPublic
。
var methodInfo = this.GetType().GetMethod("AddText", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null);
Your method has a parameter, you need to use the overload that accepts a type array for the parameter types and the binding flags. 您的方法有一个参数,您需要使用接受类型数组的重载作为参数类型和绑定标志。
In .net Method signatures are based on their name, their return type, and their parameters. 在.net方法中,签名基于其名称,返回类型及其参数。
So if your method has parameters you have to tell Reflection what parameter types it has via a Type[]. 因此,如果您的方法有参数,您必须通过Type []告诉Reflection它具有哪些参数类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.