Home > Software design >  Reference a function in a class
Reference a function in a class

Time:05-04

I want to create a class with references to functions to run. Example code which does not create a reference but runs the function upon creation

public class Jobs
{
    public List<Job> jobs;

    public Jobs()
    {
        jobs = new List<Job>()
        {
            new Job()
            {
                name = "Job 1",
                job =  func1() // This runs the function, how do I create a reference to run it later in RunJobs?
            },
            new Job()
            {
                name = "Job 2",
                job =  func1()
            }
        };

    }
    

    private async Task func1()
    {
        // do some stuff    
    }
    private async Task func2()
    {
        // do some other stuff    
    }

    public void RunJobs()
    {
        foreach(Job job in jobs) // Iterating through jobs
        {
            Console.WriteLine(job.name);
            job.job(); // I want to run the referenced function here
        }
    }

}

public class Job
{
    public string name;        
    public Task job; 

}

How can I reference func1() and func2() and run them by calling a method in the class when iterating through Jobs.

CodePudding user response:

you can add a delegate to your object to be invoked at a later time. C# provides some generic delegates you can use:

public class Job
{
    public string name;        
    public Func<Task> job; 
}
...
new Job()
{
      name = "Job 2",
      job =  func1
}

...
foreach(Job job in jobs) // Iterating through jobs
{
     Console.WriteLine(job.name);
     var myTask = job.job(); // I want to run the referenced function here
}

CodePudding user response:

I hope this is what your expecting!

public class Jobs
{
    public List<Job> jobs;

    public Jobs()
    {
        jobs = new List<Job>()
        {
            new Job()
            {
                name = "Job 1",
                job = func1
            },
            new Job()
            {
                name = "Job 2",
                job =  func2
            }
        };

    }


    private async Task func1()
    {
        // do some stuff    
    }
    private async Task func2()
    {
        // do some other stuff    
    }

    public void RunJobs()
    {
        foreach (Job job in jobs) // Iterating through jobs
        {
            Console.WriteLine(job.name);
            job.job(); // I want to run the referenced function here
        }
    }

}

public class Job
{
    public string name;
    public delegate Task _job();
    public _job job;
}
  •  Tags:  
  • c#
  • Related