简体   繁体   English

如何创建一个属性是另一个类的集合?

[英]How do create a class property that is a collection of another class?

I have classes for Client, Project and Task. 我有Client,Project和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. 在数据库中,每个数据库都有一个ID字段,而项目表有一个clientid字段。 Also, the Tasks table has a projectid field. 此外,“任务”表具有一个projectid字段。

Can someone help me with the scenario so I can make each a class? 有人可以帮助我解决这种情况,以便让我每个人都上一堂课吗?

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> . 您需要创建一个集合类型的属性,例如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? 但是 - 有一个决定:任何外部类是否具有直接从Projects集合属性添加或删除项目的完全访问权限,或者外部类只能读取集合?

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. 作为IList<Project>ICollection<Project>公开可能是个好主意,具体取决于您希望其他类能够执行的操作。

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. 如果其他类不能自由访问列表,您可能希望将其公开为IEnumerable<Project>以便他们所能做的就是遍历列表。 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. 此外,如果没有其他类具有直接访问权限,那么您将不得不向Client类添加方法以允许添加和/或删除项目。

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. 例如,如果属性是IEnumerable<Project> ,则可以将内部代码从List<Project>更改为数组( Project[] ),而不需要知道其他代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM