Evonet
Evonet

Reputation: 3640

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!

Upvotes: 0

Views: 596

Answers (1)

DocMax
DocMax

Reputation: 12164

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.

Upvotes: 4

Related Questions