c#的泛型
2016-05-18 13:59
501 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestAllHere { public class MyList<T> { private Node head; //内部类 //T对嵌套类依然有效 private class Node { private Node next; private T data; public Node(T t) { next = null; data = t; } public Node Next { get { return next; } set { next = value; } } //T作为属性的返回类型 public T Data { get { return data; } set { data = value; } } } //构造函数 public MyList() { head = null; } //添加 //T作为方法的参数类型 public void AddHead(T t) { Node n = new Node(t); n.Next = head; head = n; } //任何集合类对象都有一个GetEnumerator()方法,该方法可以返回一个实现了 IEnumerator接口的对象, //这个返回的IEnumerator对象既不是集合类对象,也不是集合的元素类对象,它是一个独立的类对象。 //通过这个对象,可以遍历访问集合类对象中的每一个元素对象 public IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } } } }
MyList<string> list = new MyList<string>(); for (int i = 0; i < 10; i++) { list.AddHead("item" + i); } foreach (string item in list) { Debug.WriteLine(item); }
//item9 //item8 //item7 //item6 //item5 //item4 //item3 //item2 //item1 //item0
MyList<int> list = new MyList<int>(); for (int i = 0; i < 10; i++) { list.AddHead(i); } foreach (int item in list) { Debug.WriteLine(item); }
//9 //8 //7 //6 //5 //4 //3 //2 //1 //0
相关文章推荐
- C#:DataTable映射成Model
- 写的非常好的文章 C#中的委托,匿名方法和Lambda表达式
- c# 学习笔记
- C#在DataTable中根据条件删除某一行的实现方法
- c# MACD 算法实现
- 用 C# 绘制曲线图(Curve图,增加自动适应和多曲线绘制)
- 【C#】调度程序进程已挂起,但消息仍在处理中;
- 字符串处理总结(C#String类)
- 转载 C#匿名函数 委托和Lambda表达式
- 关于c#在DataTable中根据条件删除某一行
- c#截取图片
- C# 格式化字符串
- C# 委托
- C#线程池多线程Socket通讯 服务器端和客户端示例
- C#Winform删除DataGridView中被选中的行
- C#Winform判断DataGridView中的checkbox列是否选中
- C#Winform技术,利用DataGridViewRow向DataGridView中添加数据
- C# 笔记——索引器
- C# 笔记——覆盖和重写
- C# 笔记——委托