首页 > 代码库 > 自定义泛型类,本质就是利用微软提供的集合和集合接口
自定义泛型类,本质就是利用微软提供的集合和集合接口
//实现IEnumerable<A>接口中的GetEnumerator()方法,为了能支持foreach遍历
class MyClass<A>:IEnumerable<A>
{
List<A> list = new List<A>();
private List<A> items;
public List<A> Items
{
get { return list;}
}
//元素个数
private int count;
public int Count
{
get { return list.Count; }
set { count = value; }
}
public void Add(A item)
{
this.list.Add(item);
}
public bool Remove(A item)
{
return this.list.Remove(item);
}
public void RemoveAt(int index)
{
this.list.RemoveAt(index);
}
#region IEnumerable<A> 成员
public IEnumerator<A> GetEnumerator()
{
return list.GetEnumerator();
}
#endregion
#region IEnumerable 成员
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
/***********自定义泛型类****************/
static void Main(string[] args)
{
MyClass<Student> myClass = new MyClass<Student>();
Student stu1 = new Student() { StuName = "张三", StuNo = "S001", StuAge = 23 };
Student stu2 = new Student() { StuName = "李四", StuNo = "S002", StuAge = 24 };
myClass.Add(stu1);
myClass.Add(stu2);
Console.WriteLine(myClass.Count);
foreach (Student item in myClass)
{
Console.WriteLine(item.StuName);
}
}
//使用
/***********排序****************/
//static void Main(string[] args)
//{
// //整型、字符串可以比较大小,所以能排序
// //ArrayList arr = new ArrayList();
// //arr.Add("aa");
// //arr.Add("ad");
// //arr.Add("ac");
// //arr.Add("aw");
// //arr.Add("ad");
// //foreach (var item in arr)
// //{
// // Console.WriteLine(item);
// //}
// //arr.Sort();//排序
// //Console.WriteLine("排序后:");
// //foreach (var item in arr)
// //{
// // Console.WriteLine(item);
// //}
// //类
// List<Student> arr = new List<Student>();
// Student stu1 = new Student() { StuName = "张三", StuNo = "S001", StuAge = 23 };
// Student stu2 = new Student() { StuName = "李四", StuNo = "S002", StuAge = 14 };
// Student stu3 = new Student() { StuName = "王五", StuNo = "S003", StuAge = 28 };
// Student stu4 = new Student() { StuName = "赵六", StuNo = "S004", StuAge = 26 };
// arr.Add(stu1);
// arr.Add(stu4);
// arr.Add(stu3);
// arr.Add(stu2);
// foreach (var item in arr)
// {
// Console.WriteLine(item.StuNo + "-" + item.StuName + "-" + item.StuAge);
// }
// //arr.Sort();//排序(实现接口)
// arr.Sort(new AgeComparerDESC());//排序(比较器)
// Console.WriteLine("排序后:");
// foreach (var item in arr)
// {
// Console.WriteLine(item.StuNo + "-" + item.StuName + "-" + item.StuAge);
// }
//}