简体   繁体   中英

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:

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?

Thanks for your help!

You are right that BindingFlags.Instance means that your method is not static. As a result, your call to GetMethod is not returning null .

Instead, the problem is that your Invoke call is supplying null instead of the object for this in the call. 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:

typeof(WorkerRole).GetMethod(string.Format("{0}GetProfiles", Firm), 
    BindingFlags.Instance | BindingFlags.Public).Invoke(this, null);

More details on Invoke is on this MSDN page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM