[英]C# - GetMethod returns null
我有A
節課:
public abstract class A
{
}
然后我有B
類派生自它:
public sealed class B : A
{
public void SomeMethod()
{
var method = this.GetType().GetMethod("AddText");
}
private void AddText(string text)
{
...
}
}
為什么GetMethod
返回null?
默認情況下,Reflection只搜索公共方法。
你需要傳遞BindingFlags.Instance | BindingFlags.NonPublic
BindingFlags.Instance | BindingFlags.NonPublic
。
var methodInfo = this.GetType().GetMethod("AddText", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null);
您的方法有一個參數,您需要使用接受類型數組的重載作為參數類型和綁定標志。
在.net方法中,簽名基於其名稱,返回類型及其參數。
因此,如果您的方法有參數,您必須通過Type []告訴Reflection它具有哪些參數類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.