[英]Using reflection to dynamically call a function gives error: Non-static method requires a target
I am trying to use reflection to call a function dynamically and not quite sure how to make it work. 我正在尝试使用反射来动态调用函数,但不确定如何使它工作。
Here's my main function: 这是我的主要功能:
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);
}
}
And here is an example of one of the functions I am dynamically calling (they all have the same signatures): 这是我动态调用的函数之一的示例(它们都具有相同的签名):
public partial class WorkerRole : RoleEntryPoint
{
public List<string> BHPGetProfiles()
{
// Do tasks specific to BHP
}
}
The error that I'm getting in the line that starts with typeof above is: 我从上述typeof开头的行中遇到的错误是:
Additional information: Non-static method requires a target. 附加信息:非静态方法需要一个目标。
I don't want to have my GetProfiles methods as static, but I thought that adding BindingFlags.Instance should have resolved this? 我不想将我的GetProfiles方法设置为静态,但我认为添加BindingFlags.Instance应该可以解决此问题?
Thanks for your help! 谢谢你的帮助!
You are right that BindingFlags.Instance
means that your method is not static. 您说对了,
BindingFlags.Instance
意味着您的方法不是静态的。 As a result, your call to GetMethod
is not returning null
. 因此,您对
GetMethod
的调用未返回null
。
Instead, the problem is that your Invoke
call is supplying null
instead of the object for this
in the call. 相反,问题是,你
Invoke
呼叫提供null
的,而不是为对象this
通话。 It should be the the first parameter. 它应该是第一个参数。 For example, if you want the method to be called for the object on which
Run()
is executing, you should use: 例如,如果要为正在执行
Run()
的对象调用该方法,则应使用:
typeof(WorkerRole).GetMethod(string.Format("{0}GetProfiles", Firm),
BindingFlags.Instance | BindingFlags.Public).Invoke(this, null);
More details on Invoke
is on this MSDN page . 有关
Invoke
更多详细信息, Invoke
MSDN页面 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.