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;
}
}
}
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;
}
}
}
相关文章推荐
- C# 2.0 中关于泛型的用法实例
- C# 2.0 中关于泛型的用法实例 收藏
- C#2.0泛型:Dictionary,List用法
- 关于C#2.0泛型应用的一个小例子
- C#中Predicate<T>与Func<T, bool>泛型委托的用法实例
- 关于c# 泛型List集合对象的用法及相关操作
- 关于c# 泛型List集合对象的用法及相关操作
- 关于C#中泛型类型参数约束(where T : class)
- 关于MySQL的init-file选项的用法实例
- C#关于DateTime得到的当前时间的格式和用法
- c#2.0新特性:(一)泛型(Generics)
- C# 2.0 泛型
- c# 泛型 list 用法
- 学习笔记(一)C#基础和泛型List和DataTable和HashTable和Dictionary的简单用法--存值 取值
- C#中WebBroeser控件用法实例教程
- C# 2.0与泛型
- C#2.0 Socket套接字编程之实例初探
- C#2.0 Socket套接字编程之实例初探
- C# .Net 2.0实例学习:WebBrowser页面与WinForm交互技巧(一)
- C#中FormsAuthentication用法实例