![](/img/trans.png)
[英]Receiving error message: System.Reflection.TargetException: Non-static method requires a target
[英]Using reflection to dynamically call a function gives error: Non-static method requires a target
我正在嘗試使用反射來動態調用函數,但不確定如何使它工作。
這是我的主要功能:
public partial class WorkerRole : RoleEntryPoint
{
public override void Run()
{
while (true)
{
List<string> Firms = new List<string>();
Firms.Add("BHP");
foreach (string Firm in Firms)
{
typeof(WorkerRole).GetMethod(string.Format("{0}GetProfiles", Firm), BindingFlags.Instance | BindingFlags.Public).Invoke(null, null);
}
break;
}
Thread.Sleep(Timeout.Infinite);
}
}
這是我動態調用的函數之一的示例(它們都具有相同的簽名):
public partial class WorkerRole : RoleEntryPoint
{
public List<string> BHPGetProfiles()
{
// Do tasks specific to BHP
}
}
我從上述typeof開頭的行中遇到的錯誤是:
附加信息:非靜態方法需要一個目標。
我不想將我的GetProfiles方法設置為靜態,但我認為添加BindingFlags.Instance應該可以解決此問題?
謝謝你的幫助!
您說對了, BindingFlags.Instance
意味着您的方法不是靜態的。 因此,您對GetMethod
的調用未返回null
。
相反,問題是,你Invoke
呼叫提供null
的,而不是為對象this
通話。 它應該是第一個參數。 例如,如果要為正在執行Run()
的對象調用該方法,則應使用:
typeof(WorkerRole).GetMethod(string.Format("{0}GetProfiles", Firm),
BindingFlags.Instance | BindingFlags.Public).Invoke(this, null);
有關Invoke
更多詳細信息, Invoke
MSDN頁面 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.