If you want to retain the current structure and simply use a generic type instead of always creating a Person
, a very straightforward refactoring looks something like this.
Create an abstract base class for the resource (a person, building, vehicle) required for a project.
public abstract class Resource
{
public virtual Assignment Job { get; set; }
public virtual Site Site { get; set; }
}
Create your concrete classes.
public class Person : Resource
{
public Person()
{
}
}
public class Building : Resource
{
public Building()
{
}
}
Now you can make your Project
class accept a generic type T
instead of Person
. In this example, T must be some derived class of Resource
and must support a parameterless constructor.
public class Project<T> where T : Resource, new()
{
public T Resource { get; set; } // will need to handle other classes as well
public String Task { get; set; }
// ctor
public Project(String task)
{
Task = task;
}
// current method
public void DoWork()
{
var work = new Work(this.Task);
Resource resource = new T(); // this instance of Person could be other objects as noted
resource.Job = work.Assignment;
resource.Site = work.Site;
// ...
}
}
You create your projects and do work like this.
Project<Person> personProject = new Project<Person>("MyTask");
personProject.DoWork();
Project<Building> buildingProject = new Project<Building>("MyBuildingTask");
buildingProject.DoWork();
You should not call DoWork
from the constructor as shown in your code sample. Create the instance first, then call the method.