I am learning how to use Interface of C#,
I reading this artcile :
http://www.codeproject.com/Articles/286863/I-Interface
One of the example:
public class TaskComposite : ITask
{
public TaskComposite(params ITask[] tasks)
{
this.composedTasks = new List<ITask>();
if(tasks != null)
{
foreach(var task in tasks)
AddTask(task);
}
}
public void Do()
{
foreach(var task in this.composedTasks)
task.Do();
}
public void AddTask(ITask task)
{
if(task != null)
this.composedTasks.Add(task);
}
private List<ITask> composedTasks;
}
The description said:
we can group a load of tasks together to be executed serially.
I create a Windows form as create a new instance of TaskComposite class, But what should i do next?
public partial class FormInterface : Form
{
public FormInterface()
{
InitializeComponent();
}
private void FormInterface_Load(object sender, EventArgs e)
{
ITask[] TaskAry = new ITask[] { };
TaskAry[0] = new TaskClass().Do(); //<=Error
TaskComposite tc = new TaskComposite(TaskAry);
}
class TaskClass : ITask
{
public void Do()
{
Console.WriteLine(DateTime.Now.ToString());
}
}
}
You have several mistakes here.
First, when you create an array, you should specify its size, or initialize it. This is a difference between collections (which has variable size) and arrays. So, you should provide size
Or initialize (size will be computed by compiler):
But in your case, when
params ITask[] tasksis used, you can simply pass list of tasks:Pattern Composite allows you to treat group of objects as single object. In your case composite task here to allow you treat several task as one task object. So, without composite task, you’ll need to use array/collection of tasks and execute each of them manually. Like this:
With composite tasks you don’t need to iterate over all tasks:
You can pass composite task where simple ITask is expected. And no one will know that there is actually a bunch of tasks.