C# 2.0 中关于泛型的用法实例

80酷酷网    80kuku.com

  

1. 定义泛型类

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
    class BList<T>
    {
        ArrayList arr = new ArrayList();

        public T this[int i]
        {
            get
            {
                return (T)arr[i];
            }
            set
            {
               arr.Add(value);
            }
        }

        public void Add(T p_obj)
        {
            arr.Add(p_obj);
        }

        public int Count
        {
            get
            {
                return arr.Count;
            }
        }

    }
}

2. 调用(放到任意的窗体事件中)
 private void button2_Click(object sender, EventArgs e)
        {

            BList<int> _list = new BList<int>(); // <int>里面可以替换任意已知类型
            for (int i = 0; i < 10; i++)
            {
                _list.Add( i);
            }

            for (int i = 0; i < _list.Count; i++)

                MessageBox.Show(_list[i].ToString());
        }

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: