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

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

2005-11-14 17:12 786 查看
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());
}

另外一个泛型集合类,可以创建所有已知类型的集合,感觉也比较方便

class MyCollection<T>
{
private int _Count;
private T [] _Array;

public MyCollection(int p_ItemCount)
{
_Count = p_ItemCount;
_Array = new T [ _Count];
}

public int Count
{
get
{
return _Count;
}
}

public T this[int index]
{
get
{
if (index > -1 && index < _Array.Length)
{
return (T)_Array[index];
}
else
return (T)(new object());
}
set
{
_Array[index] = (T)value;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: