c#中的集合

本文关键字:集合 | 更新日期: 2023-09-27 18:18:22

我有c++背景,我正在努力自学c#。我还是一个学生,这不是学校的项目,我现在休息。我主要关注的是C/c++, java

我有一个2年前的旧学校项目,我用c++做了一个存储DVD,书籍,DVD,信息的容器,然后显示它。我正在尝试用c#

制作相同的程序。

我有两个非常相似的问题…

在我的程序中,对容器使用了类型定义,并创建了容器的对象,如下所示:

typedef set<Item*>  ItemSet;
ItemSet allBooks;            // holds all the information
ItemSet allCDS;
ItemSet allDVDs;

第一个问题是c#中没有typdef,我认为它的等效是使用?但是我不能在容器上使用它。是否有一种方法可以在c#中做类似的事情,或者我应该创建多个集合?我决定Hashset类似于c++中的set

HashSet<Item> keys = new HashSet<Item>();

第二个问题是它还在类外的集合上使用了typedef,然后在私有部分使用了typedef我做了一组对象。我可以在c#中做到这一点吗?

typedef set<string> StringSet;
class Item
{
 private:
 string Title;
 StringSet* Keys;      // holds keywords

我意识到c#没有指针!

c#中的集合

c#没有类似typedef的东西。您只需直接使用类型名。

HashSet<Item> allBooks = new HashSet<Item>(); 
HashSet<Item> allCDs= new HashSet<Item>(); 
HashSet<Item> allDVDs = new HashSet<Item>(); 
HashSet<string> keys = new HashSet<string>(); 

所以…

class Item
{
    private string title;
    private HashSet<string> keys = new HashSet<string>();      // holds keywords

using语句声明了编译器在解析类型名时应该搜索的名称空间。因此,要使上述工作,您需要

using System.Collections.Generic; 

在源文件的顶部。

如果没有using语句,您将不得不执行

System.Collections.Generic.HashSet<Item> allBooks = new System.Collections.Generic.HashSet<Item>(); 

在c#中没有类似于c++的typedef的概念。为了使您的工作更轻松并节省一些输入,c#允许您在局部变量的声明/初始化中跳过类型:

var keys = new HashSet<Item>();

相同
HashSet<Item> keys = new HashSet<Item>();

仍然需要在成员声明中使用完整类型。然而,将成员声明为接口而不是精确类型是一个很好的实践:

class MyClass {
    ISet<Item> allBooks = new HashSet<Item>();
}

这可以让您在以后的时间切换实现,而不必更改代码中的任何其他内容。

c#没有显式地有typedef,最接近的是using声明来创建类型别名。在c#文件的顶部,你可以这样做:

using StringSet = System.Collections.Generic.HashSet<string>;

然后你可以这样做:

var set = new StringSet();

有一个与using指令等价的typedef,但我还没有看到它被普遍使用。通常使用完整类型。如果你有需要,(例如,你需要在项目集合的同时存储其他数据)创建一个像public class ItemSet : List<Item>这样的类。

HashSet<T>应该在集合不包含相同项两次或多次时使用,并且Object.EqualsObject.GetHashCode方法对您的数据类型是有意义的(默认情况下,它们本质上标识实例,而不是对象的值)。它将自动使用这些属性来添加一个对象,如果该对象还不存在于集合中。更常见的方法是使用List<T>来存储项。根据我对你情况的一点了解,List<T>应该可以工作。

所以我建议这样写:

class Item
{
    private string Title;
    List<string> Keys;      // holds keywords
}

:

List<Item> allBooks = new List<Item>(); 
List<Item> allCDs= new List<Item>(); 
List<Item> allDVDs = new List<Item>();