主程序1
</pre><pre name="code" class="csharp">internal class Program
{
private static void Main(string[] args)
{
MyArrayList mylist = new MyArrayList();
mylist.Add("yushangyong");
mylist.Add("gaowenmi");
mylist.Add("yanliupan");
mylist.Add("lirende");
mylist.Add("lijingjing");
mylist.Sort();
}
}
internal class MyArrayList
{
private ArrayList _list = new ArrayList();
public void Add(object obj)
{
_list.Add(obj);
}
public object this[int index]
{
get { return _list[index]; }
}
public void Sort()
{
//自己写一个冒泡排序法,对_list中的内容进行排序
for (int i = 0; i < _list.Count - 1; i++)
{
for (int j = _list.Count - 1; j > i; j--)
{
IComparable obj1 = _list[j] as IComparable;
IComparable obj2 = _list[j - 1] as IComparable;
//判断集合中的元素是否可以成功转换为IComparable接口类型
if (obj1 != null && obj2 != null)
{
if (obj1.CompareTo(obj2) < 0)//string类型继承Icomparable接口,所以可以用CompareTo方法
{
object tmp = _list[j];
_list[j] = _list[j - 1];
_list[j - 1] = tmp;
}
}
else
{
throw new ArgumentException();
}
}
}
}
public void Remove(object obj)
{
_list.Remove(obj);
}
public int Count
{
get { return _list.Count; }
}
}
主程序2
internal class Program
{
private static void Main(string[] args)
{
MyArrayList mylist = new MyArrayList();
mylist.Add(new Person() { Name = "yushangyong", Age = 10 });
mylist.Add(new Person() { Name = "gaowenmi", Age = 13 });
mylist.Add(new Person() { Name = "yanliupan", Age = 20 });
mylist.Add(new Person() { Name = "lirende", Age = 7 });
mylist.Add(new Person() { Name = "lijingjing", Age = 6 });
mylist.Sort(new PersonSortByNameLengthDesc());//相当于子类对象赋予父类(接口),为了调用子类的函数
for (int i = 0; i < mylist.Count; i++)
{
Console.WriteLine(((Person)mylist[i]).Name);
}
}
}
public class PersonSortByNameLengthDesc : IComparer
{
public int Compare(object x, object y)
{
Person p1 = x as Person;
Person p2 = y as Person;
return p2.Name.Length - p1.Name.Length;
}
}
internal class MyArrayList
{
private ArrayList _list = new ArrayList();
public void Add(object obj)
{
_list.Add(obj);
}
public object this[int index]
{
get { return _list[index]; }
}
//参数是一个比较器,需要自己写一个类来实现。
public void Sort(IComparer comparer)
{
//自己写一个冒泡排序法,对_list中的内容进行排序
for (int i = 0; i < _list.Count - 1; i++)
{
for (int j = _list.Count - 1; j > i; j--)
{
if (comparer.Compare(_list[j], _list[j - 1]) < 0)
{
object tmp = _list[j];
_list[j] = _list[j - 1];
_list[j - 1] = tmp;
}
}
}
}
public void Remove(object obj)
{
_list.Remove(obj);
}
public int Count
{
get { return _list.Count; }
}
}