c#的泛型

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值