什么是C#中的泛型集合? [英] What are Generic Collections in C#?

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

问题描述

我正在尝试构建我的第一个通用列表,并遇到了一些问题。我知道该声明看起来像 List< T> ,并且我有使用System.Collections.Generic; at我的页面顶部。但是,Visual Studio不能识别 T 变量。



我缺少什么?

解决方案

List< T> 表示 List< WhateverTypeYouWantItToBeAListOf> 。例如:

如果我有一个Employee Class,并且我想要一个Employees集合,我可以这样说:

 列表与LT;员工> employeeList = new List< Employee>(); 

然后,我可以将 Employee 对象添加到列表中,并使其成为类型安全的,并扩展到我放入其中的许多员工对象。



像这样:

 员工emp1 =新员工(); 
Employee emp2 = new Employee();

employeeList.Add(emp1);
employeeList.Add(emp2);

employeeList 现在持有 emp1 emp2 作为对象。



泛型集合有几个方面,最重要的是它们提供了一个独立于对象的方式,包含一个...好的...对象集合。它们是类型安全的;这意味着任何集合都将由一种类型的对象组成。在 List< Employee> 中不会有 Animal 实例(当然,除非Employee是基础 自己的话题,值得(至少)一本书的一章。在非常高的层次上,泛型编程提供了另一种重用代码的方式 - 独立于任何类层次结构或特定类的实现细节。



更多信息此处 a>。


I'm trying to build my first generic list and have run into some problems. I understand the declaration looks like " List<T> ", and I have using System.Collections.Generic; at the top of my page. However, Visual Studio doesn't recognize the T variable.

What am I missing?

解决方案

List<T> means List<WhateverTypeYouWantItToBeAListOf>. So for example:

If I have an Employee Class, and I wanted a collection of Employees, I could say:

List<Employee> employeeList = new List<Employee>();

I could then add Employee Objects to that list, and have it be Type-safe and extend to however many employee objects I put in it.

Like so:

Employee emp1 = new Employee();
Employee emp2 = new Employee();

employeeList.Add(emp1);
employeeList.Add(emp2);

employeeList now holds emp1 and emp2 as objects.

There are several facets to generic collections, the most important being they provide an object independent way of having a... well... collection of objects. They are type-safe; which means that any collection will consist of one type of object. You won't have a Animal instance inside of List<Employee> (unless, of course, Employee is a base class that Animal inherits from. At that point, however, you have bigger problems.

Programming with Generics is its own topic, worthy of (at least) one chapter in a book. At a very high level, programming with generics provides another way to reuse code -- independent of any class hierarchy or implementation details of a specific class.

More information here.

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

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