大概有以下几个C#泛型集合类型:
1. List,这是我们应用最多的泛型种类,它对应ArrayList集合。
2. Dictionary,这也是我们平时运用比较多的泛型种类,对应Hashtable集合。
3. Collection对应于CollectionBase
4. ReadOnlyCollection 对应于ReadOnlyCollectionBase,这是一个只读的集合。
5. Queue,Stack和SortedList源码天空,它们分别对应于与它们同名的非泛型类。
看一下这个类:
- PersonCollection
- public class PersonCollection : IList
- {
- private ArrayList _Persons = new ArrayList();
- public Person this[int index]
- { get { return (Person) _Persons[index]; } }
- public int Add(Person item)
- {
- _Persons.Add(item);
- return _Persons.Count - 1;
- }
- public void Remove(Person item)
- { _Persons.Remove(item); }
- object IList.this[int index]
- {
- get { return _Persons[index]; }
- set { _Persons[index] = (Person)value; }
- }
- int IList.Add(object item)
- { return Add((Person)item); }
- void IList.Remove(object item)
- { Remove((Person)item); }
- }
这个类是Person类的操作类,可以自由的增加或删除Person类.如果现在要为其他的类写一个功能与这个类一样的操作类,相信只需要将Person类替换一下就可以了.不过在了解泛型之后你就可以这样来用.
- List﹤Person﹥ persons = new List﹤Person﹥();
- persons.Add(new Person());
- Person person = persons[0];
比如,如果要将Person类换成Employee类,只需要像这样写.
- List﹤Employee﹥ employees= new List﹤Employee﹥();
- employees.Add(new Employee());
- Employee employee= employees[0];
List是C#中已经定义好的泛型类,现在我们可以自己定义它.
- TypeHelper
- public class TypeHelper﹤T﹥
- {
- public String GetType(T t){
- return "Type is "+t.GetType().toString();
- }
- }
这里的T只是一个类型的占位符,在实际应用的时候,将实际的类型替换掉T就可以.
- TypeHelper﹤Person﹥ typeHelper = new TypeHelper();
- typeHelper.GetType(Person);
注意T只是一个占位符,实际上换上任何符号都可以,千万不要任为只有T可以做占位符.
有的时候我们必须要约束一下实际的类型,比如以下的泛型类.
C#泛型集合类型的使用基本内容就向你介绍到这里,希望对你了解和学习C#泛型集合类型有所帮助。
- CollectionHelper
- public class CollectionHelper﹤T,V﹥
- {
- private T Collec = new T();
- public int IndexOf(V v){
- return Collec.IndexOf(v);
- }
- }
泛型类中的T,V显示不是随便什么类型都可以代替的,首先这个类型T必须具有IndexOf方法,V必须是一个引用类型.所以这个类要修改一下.
- CollectionHelper
- public class CollectionHelper﹤T,V﹥ where T:IList
- where V:class
- {
- private T Collec = new List();
- public int IndexOf(V v){
- return Collec.IndexOf(v);
- }
- }
where 是关键字,T是表示所要进行约束的类型.IList是表示要实现的接口,显示只要实现IList接口,就一定有IndexOf方法,V的约束是必须是一个类.
如果要求类型必须是一个值类型的参数,就需要使用struct.如果还需要将类型重新实例化就需要使用new()来进行限制,说明该类型必须要有一个无参的构造函数.
注意如果一个类型需要有多个约束进行限制,那么new()必须写在最后面.
泛型也可以用到委托里叫泛型委托,不过对于委托本人不是很熟,相信都是大同小异.