How do create a class property that is a collection of another class?
I have classes for Client, Project and Task.
Each Client contains multiple projects. Each Project contains multiple Tasks.
In the database each has an ID field, and the project table has a clientid field. Also, the Tasks table has a projectid field.
Can someone help me with the scenario so I can make each a c开发者_开发技巧lass?
Here it is:
public class Client
{
public int Id {get;set;}
// Client Properties
private List<Project> _projects = new List<Project>();
public List<Project> Projects { get { return _projects; } }
}
public class Project
{
public int Id { get; set; }
public int ClientId { get; set; }
// Project Properties
private List<Task> _tasks = new List<Task>();
public List<Task> Tasks { get { return _tasks; } }
}
public class Task
{
public int Id { get; set; }
public int ProjectId { get; set; }
// Task Properties
}
You need to make a property of a collection type, like List<Project>
.
However -- there is a decision to be made: Will any external class have full access to add or remove projects directly from the Projects collection property, or will external classes only be able to read the collection?
If any other class can have full access to the Project list, then you need to choose the external type that the list will be exposed as. It might be a good idea to expose as an IList<Project>
or an ICollection<Project>
depending on that you want other classes to be able to do.
If other classes will not have free access to the list, you might want to expose it as an IEnumerable<Project>
so that all they can do is iterate through the list. Additionally, if no other classes have direct access, then you are going to have to add methods to the Client class to allow Projects to be added and/or removed.
By only allowing interface-based external access to the list of projects, you free yourself to change the underlying data structure to another compatible one without breaking any other code. For example, if the property is an IEnumerable<Project>
, you could change the internal code from a List<Project>
to an array (Project[]
) and no other code needs to know.
精彩评论