- 集合的本质是一个类,它至少实现了IEnumerable接口,因此,IEnumerable接口使类成为集合。
- 为了使集合更加规范,通常也会实现ICollection接口和索引器。
- 实现方法时注意异常判断,以下只是基本功能实现。
using System;
using System.Collections;
using System.Collections.Generic;
namespace _23
{
class Program
{
static void Main(string[] args)
{
CustomCollection collection = new CustomCollection();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
collection.Add(5);
IEnumerator enumerator = collection.GetEnumerator();
while (enumerator.MoveNext())
{
Console.Write($"{enumerator.Current}t");
}
Console.WriteLine();
Console.WriteLine($"是否包含3:{collection.Contains(3)}");
Console.WriteLine($"是否包含6:{collection.Contains(6)}");
int[] array = new int[5];
collection.CopyTo(array, 0);
foreach (var item in array)
{
Console.Write($"{item}t");
}
Console.WriteLine();
collection.Remove(2);
foreach (var item in collection)
{
Console.Write($"{item}t");
}
Console.WriteLine();
collection.Clear();
Console.WriteLine($"元素个数:{collection.Count}");
}
}
class CustomCollection : IEnumerable, ICollection
{
private T[] items;
private int count;
public CustomCollection()
{
items = new T[4];
count = 0;
}
public CustomCollection(int capacity)
{
items = new T[capacity];
count = 0;
}
///
/// 索引器
///
///
///
public T this[int index]
{
get
{
return items[index];
}
set
{
items[index] = value;
}
}
public int Count => count;
public bool IsReadOnly => false;
public void Add(T item)
{
if (count == items.Length)
{
SetCapacity(items.Length * 2);
}
items[count++] = item;
}
public void Clear()
{
if (count > 0)
{
Array.Clear(items, 0, count);
count = 0;
}
}
public bool Contains(T item)
{
for (int i = 0; i < count; i++)
{
if (items[i].Equals(item))
{
return true;
}
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(items, 0, array, arrayIndex, count);
}
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
Array.Copy(items, index + 1, items, index, count - index - 1);
count--;
return true;
}
return false;
}
///
/// 迭代器
///
///
public IEnumerator GetEnumerator()
{
for (int i = 0; i < count; i++)
{
yield return items[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void SetCapacity(int capacity)
{
T[] array = new T[capacity];
if (count > 0)
{
Array.Copy(items, array, count);
}
items = array;
}
public int IndexOf(T item)
{
for (int i = 0; i < count; i++)
{
if (items[i].Equals(item))
{
return i;
}
}
return -1;
}
}
}