C#實現IDictionary接口
最近學習.Net開發,發現自己跟着實現一個微軟官方文檔的例子,對自己理解一些相關的數據結構和用法有相當好的幫助,所以這裏跟着文檔上的例子實現了IDictionary接口,實現了一個字典類型的基本功能。所以代碼寫在這裏,記錄一下自己的學習過程。
IDictionary接口的實現過程代碼如下:
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
namespace 類型_Type
{
/// <summary>
/// This class implements a simple dictionary using an array of dictionary
/// DictionaryEntry objects
/// </summary>
class SimpleDictionary :IDictionary
{
// The array of items
public DictionaryEntry[] items;
private Int32 ItemsInUse;
// Construct the SimpleDictionary with desired number of items
// The number of items can not change for the life time of this SimpleDictionary
public SimpleDictionary(Int32 numItems)
{
items = new DictionaryEntry[numItems];
}
#region IDictionary Members
public bool IsReadOnly { get { return false; } }
public bool Contains(object key)
{
Int32 index;
return TryGetIndexOfKey(key, out index);
}
public bool IsFixedSize { get { return false; } }
public void Remove(object key)
{
if (key == null) throw new ArgumentNullException();
// Try to find out the key in DictionaryEntry array
Int32 index;
if(TryGetIndexOfKey(key,out index))
{
// If key is found,slide all the items up
Array.Copy(items, index + 1, items,index, ItemsInUse - index - 1);
ItemsInUse--;
}
else
{
// If the key is not the dictionary just return;
return;
}
}
public void Clear() { ItemsInUse = 0; }
public void Add(object key,object value)
{
// Add the new key/value pair even if this key already exists in the dictionary
if(ItemsInUse==items.Length)
{
throw new InvalidCastException("The dictionary could not hold any more items");
}
else
{
items[ItemsInUse++] = new DictionaryEntry(key, value);
}
}
public ICollection Keys
{
get
{
object[] keys = new object[ItemsInUse];
for(Int32 i=0;i<ItemsInUse;i++)
{
keys[i] = items[i].Key;
}
return keys;
}
}
public ICollection Values
{
get
{
object[] values = new object[ItemsInUse];
for(Int32 i=0;i<ItemsInUse;i++)
{
values[i] = items[i].Value;
}
return values;
}
}
public int Count { get { return ItemsInUse; } }
public object SyncRoot { get { throw new NotImplementedException(); } }
public bool IsSynchronized { get { return false; } }
public object this[object key]
{
get
{
// If this key is in the dictionary then return its value
Int32 index;
if(TryGetIndexOfKey(key,out index))
{
// The key was foun then return its value
return items[index].Value;
}
else
{
// The key was not found then return null
return null;
}
}
set
{
// If the key is in the dictionary then change its value
Int32 index;
if(TryGetIndexOfKey(key,out index))
{
// The key was found then change its value
items[index].Value = value;
}
else
{
// The key was not found then add this key/value pair
Add(key, value);
}
}
}
private bool TryGetIndexOfKey(object key, out int index)
{
for(index=0;index<ItemsInUse;index++)
{
if(items[index].Key == key)
{
return true;
}
}
return false;
}
public IDictionaryEnumerator GetEnumerator()
{
// Construct and return an enumrator
return new SimpleDictionaryEnumrator(this);
}
public void CopyTo(Array array, int index)
{
}
IEnumerator IEnumerable.GetEnumerator()
{
// Construct and return an enumerator.
return new SimpleDictionaryEnumrator(this);
}
#endregion
}
class SimpleDictionaryEnumrator : IDictionaryEnumerator
{
// A copy of the SimpleDictionary object's key/value
public DictionaryEntry[] items;
Int32 Index = -1;
public SimpleDictionaryEnumrator(SimpleDictionary sp)
{
items = new DictionaryEntry[sp.Count];
Array.Copy(sp.items, 0, items,0, sp.Count);
}
// Return the current items
public object Current
{
get
{
ValidateIndex();
return items[Index];
}
}
public object Key { get { ValidateIndex();return items[Index].Key; } }
public object Value { get { ValidateIndex();return items[Index].Value; } }
public DictionaryEntry Entry { get { return items[Index]; } }
private void ValidateIndex()
{
if(Index<0 || Index>=items.Length)
{
throw new InvalidOperationException("Enumrator is before or after the collection");
}
}
public bool MoveNext()
{
if(Index<items.Length-1)
{
Index++;
return true;
}
return false;
}
public void Reset()
{
Index = -1;
}
}
class Program
{
static void Main(string[] args)
{
// Create a dictionary that contains no more than three entries
IDictionary d = new SimpleDictionary(5);
d.Add("English", 70);
d.Add("French", 80);
d.Add("Math", 90);
Console.WriteLine($"Number of elements in dictionary={d.Count}");
Console.WriteLine($"Your English score is:{d["English"]}");// 按key來查詢
//刪除一個存在的鍵值對
d.Remove("Math");
Console.WriteLine($"After remove,The Number of elements in dictionary={d.Count}");
Console.WriteLine("字典d中的所有鍵爲如下:");
// 遍歷
foreach(string str in d.Keys)
{
Console.WriteLine(str);
}
//遍歷鍵值對
Console.WriteLine("遍歷鍵值對");
foreach(DictionaryEntry de in d)
{
Console.WriteLine($"鍵:{de.Key}\t值:{de.Value}");
}
Console.ReadKey();
}
}
}
// 代碼的運行結果如下:
//Number of elements in dictionary=3
//Your English score is:70
//After remove, The Number of elements in dictionary=2
//字典d中的所有鍵爲如下:
//English
//French
//遍歷鍵值對
//鍵:English 值:70
//鍵:French 值:80