您的位置:首页 > 编程语言 > C#

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: