I have a Reflection method, which I load an Instance of an class with a specific name. I have an abstract class which define my classes. Now I also have an interface in the constructor of this abstract class. It's a bit hard to explain and I'm not sure if it's a correct way to implement my problem. But here is my source code, which should explain the most:
Program:
private static void Main(string[] args)
{
int result;
if (args.Length > 0)
{
string jobName = args[0];
Type[] types = Assembly.GetAssembly(typeof(Task)).GetTypes();
foreach (Type type in types)
{
if (type.Name == jobName)
{
//Here is my problem. I need my Interface instead of null
_job = (Task)Activator.CreateInstance(type, null);
}
}
if (_job != null)
{
result = _job.Run(args);
}
}
//Dispose the Job
_job = null;
}
Task:
public abstract class Task
{
public IArgument Argument;
protected Task(IArgument argument)
{
Argument = argument;
}
public int Run(string[] args)
{
int result;
if (SetArguments(args))
{
result = Work();
}
return result;
}
protected abstract int Work();
Interface:
public interface IArgument
{
bool SetArguments(string[] args);
}
Now I can create an "Task" class and an "Argument" class:
public class ImportArgument : IArgument
{
public bool SetArguments(string[] args)
{
return true;
}
}
public class ImportTask : Task
{
protected override int Work()
{
return 1;
}
public ImportTask(IArgument argument) : base(argument)
{
Argument = new ArticleImportArgument();
}
}
What do you guys think. Is there a way where I can create an Instance of the task class with an Interface in the constructor? Is there another way to solve this problem? I could also create an abstract method in my Task class where I have to implement my Interface, but I think the constructor would be a better way.
Aucun commentaire:
Enregistrer un commentaire