具体实体集合类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TableToCollection.实体;
namespace 集合.集合.灵活性好的集合
{
public class PersonBaseCollection:BaseCollection
{
}
}
客户端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TableToCollection.实体;
using TableToCollection.集合.灵活性差的集合;
using 集合.集合.灵活性好的集合;
using 集合.灵活性差的ORMapping.ORMapping;
namespace 集合
{
class Program
{
static void Main(string[] args)
{
#region 灵活性差的集合
//#region 灵活性差的集合
//PersonCollection_bad personCollection = new PersonCollection_bad();
////集合添加元素
//for (int i = 0; i < 10; i++)
//{
// Person p = new Person() { strID=i.ToString(),strName="zhang",intAge=i};
// personCollection.Add(p);
//}
//Console.WriteLine("元素个数:"+personCollection.Count);
////输出集合
//Console.WriteLine("使用foreach输出");
//foreach (var item in personCollection)
//{
// Console.WriteLine(((Person)item).strID + ((Person)item).strName + ((Person)item).intAge);
//}
//Console.WriteLine("使用for输出");
//for (int i = 0; i < personCollection.Count; i++)
//{
// Console.WriteLine(((Person)personCollection[i]).strID + ((Person)personCollection[i]).strName + ((Person)personCollection[i]).intAge);
//}
//#endregion
#endregion
#region 灵活性好的集合
PersonBaseCollection personBaseCollection = new PersonBaseCollection();
DoAdd(personBaseCollection);
DoForPrint(personBaseCollection);
DoInsert(0,personBaseCollection);
DoForEachPrint(personBaseCollection);
personBaseCollection.RemoveAt(1);
DoForEachPrint(personBaseCollection);
personBaseCollection.Clear();
DoForEachPrint(personBaseCollection);
#endregion
Console.ReadKey();
}
static void DoAdd(PersonBaseCollection personBaseCollection)
{
personBaseCollection.Add(new Person() { strID = "1", strName = "qs1(Add)", intAge = 21 });
Person[] persons = { new Person() { strID = "2", strName = "qs2(AddRange)", intAge = 22 }, new Person() { strID = "3", strName = "qs3(AddRange)", intAge = 23 } };
personBaseCollection.AddRange(persons);
}
static void DoInsert(int index, PersonBaseCollection personBaseCollection)
{
personBaseCollection.Insert(index, new Person() { strID = "4", strName = "qs4(Insert)", intAge = 24 });
}
static void DoForPrint(PersonBaseCollection personBaseCollection)
{
Console.WriteLine("For语句输出:");
if (personBaseCollection.Count == 0)
{
Console.WriteLine("集合里面没有元素!");
return;
}
for (int i = 0; i < personBaseCollection.Count; i++)
{
Console.WriteLine(personBaseCollection[i].strID + " " + personBaseCollection[i].strName + " " + personBaseCollection[i].intAge);
}
}
static void DoForEachPrint(PersonBaseCollection personBaseCollection) {
Console.WriteLine("ForEach语句输出:");
if (personBaseCollection.Count == 0)
{
Console.WriteLine("集合里面没有元素!");
return;
}
foreach (var item in personBaseCollection)
{
Console.WriteLine(item.strID +" "+ item.strName +" "+ item.intAge);
}
}
}
}
总结
上面说的内容中还有一块没有说,就是迭代器设计模式,其实上面的程序中已经运用了,只不过相应的接口是微软给定义好的,为什么微软给定义好了的呢?因为微软自己也要用(.net framework提供的具体集合类)。