类中的集合类 [英] A Collection Class Within a Class

查看:81
本文介绍了类中的集合类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单且基本的面向对象的设计主题,但是……嗯,我以前没有做过,而且我在Internet上找不到合适的解决方案.

如何创建一个以集合或数组作为其属性之一的类?

例如,如果我有以下课程:
-学生,针对单个学生
-学生,针对一组学生(收藏班)
-讲习班,用于可能有几个学生的讲习班

我应该如何设计Workshop类?它应该具有学生"收藏集还是应该具有一系列学生课程?

无论您提供什么建议,请您提供Workshop类的示例代码,以及来自Workshop类的使用者的示例代码,以添加和操纵学生的数组"或集合"?

我已经知道如何开发Collection类,但是很难将Collection作为属性添加到Workshp类中.


谢谢.

This is probably a very simple and basic object oriented design topic, but ..., well, I have not done that before and I could not find a suitable solution on the Internet.

How do you create a class which has a collection or array as one of its properties?

For example, if I have the following classes:
- Student, for an individual student
- Students, for a group of students (the collection class)
- Workshop, for a workshop which may have several students

How should I design the Workshop class? Should it have a Students collection or should it have an array of student classes?

Whichever recommendation you provide, would you please provide sample code for the Workshop class and also from consumer of the Workshop class on adding and manipulating the "array" or the "collection" of students?

I already know how to develop a Collection class, but I have difficulty adding the collection as a property into the Workshp class.


Thanks.

推荐答案

我会这样:

I would do it this way:

public class Student
{
}

public class Workshop
{
    public List<student> Students {get; private set;}

    public Workshop()
    {
        Students = new List<student>();
    }

}</student></student>




这是一种更安全的实施方式.避免空引用异常.




This is a safer way to implement. Avoids null reference exception.


public class Student
{
}

public class Roster : List<Student>
{
}

public class Workshop : Roster
{
}

// or

public class Workshop
{
    Roster roster = new Roster();
}



我喜欢创建一个从List继承的类,因为以后使用它时它会更干净(而且您不必记住列表中包含的对象的类型).这个:



I like to create a class that inherits from List because it''s cleaner when you use it later (and you don''t have to remember the type of object the list contains). This:

Roster roster = new Roster()
public Roster GetRoster(){}


比这更干净:


is much cleaner than this:

List>Student< roster = new List<Student>()
public List<Student> GetRoster(){}


您可以有两个类-
You can have two classes -
class Student
{
   //Some properties
}

//Wirk shop class containing a Students collection
class WorkShop
{
   List<student> Students {get;set;}
}


这篇关于类中的集合类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆