public class MyDictionary<TKey, TValue> { private List<MyKeyValuePair<TKey, TValue>> pairs;
publicMyDictionary() { pairs = new List<MyKeyValuePair<TKey, TValue>>(); }
//索引器 public TValue this[TKey key] { get { foreach (var v in pairs) { if (v.Key.Equals(key)) return v.Value; } thrownew KeyNotFoundException(); } set { foreach (var v in pairs) { if (v.Key.Equals(key)) v.Value = value; } } }
publicboolContainsKey(TKey key) { foreach (var item in pairs) { if (item.Key.Equals(key)) returntrue; } returnfalse; }
publicvoidAdd(TKey key, TValue value) { if (ContainsKey(key)) this[key] = value; else pairs.Add(new MyKeyValuePair<TKey, TValue>() { Key = key, Value = value }); } }
public class MyDictionary<TKey, TValue> : IEnumerable<MyKeyValuePair<TKey,TValue>> { private List<MyKeyValuePair<TKey, TValue>> pairs;
publicMyDictionary() { pairs = new List<MyKeyValuePair<TKey, TValue>>(); }
public TValue this[TKey key] { get { foreach (var v in pairs) { if (v.Key.Equals(key)) return v.Value; } thrownew KeyNotFoundException(); } set { foreach (var v in pairs) { if (v.Key.Equals(key)) v.Value = value; } } }
publicboolContainsKey(TKey key) { foreach (var item in pairs) { if (item.Key.Equals(key)) returntrue; } returnfalse; }
publicvoidAdd(TKey key, TValue value) { if (ContainsKey(key)) this[key] = value; else pairs.Add(new MyKeyValuePair<TKey, TValue>() { Key = key, Value = value }); }