using System.Collections.Generic; using System.Linq; using LeanCloud.Utilities; namespace LeanCloud.Storage.Internal { /// /// Provides a Dictionary implementation that can delegate to any other /// dictionary, regardless of its value type. Used for coercion of /// dictionaries when returning them to users. /// /// The resulting type of value in the dictionary. /// The original type of value in the dictionary. [Preserve(AllMembers = true, Conditional = false)] public class FlexibleDictionaryWrapper : IDictionary { private readonly IDictionary toWrap; public FlexibleDictionaryWrapper(IDictionary toWrap) { this.toWrap = toWrap; } public void Add(string key, TOut value) { toWrap.Add(key, (TIn)Conversion.ConvertTo(value)); } public bool ContainsKey(string key) { return toWrap.ContainsKey(key); } public ICollection Keys { get { return toWrap.Keys; } } public bool Remove(string key) { return toWrap.Remove(key); } public bool TryGetValue(string key, out TOut value) { TIn outValue; bool result = toWrap.TryGetValue(key, out outValue); value = (TOut)Conversion.ConvertTo(outValue); return result; } public ICollection Values { get { return toWrap.Values .Select(item => (TOut)Conversion.ConvertTo(item)).ToList(); } } public TOut this[string key] { get { return (TOut)Conversion.ConvertTo(toWrap[key]); } set { toWrap[key] = (TIn)Conversion.ConvertTo(value); } } public void Add(KeyValuePair item) { toWrap.Add(new KeyValuePair(item.Key, (TIn)Conversion.ConvertTo(item.Value))); } public void Clear() { toWrap.Clear(); } public bool Contains(KeyValuePair item) { return toWrap.Contains(new KeyValuePair(item.Key, (TIn)Conversion.ConvertTo(item.Value))); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { var converted = from pair in toWrap select new KeyValuePair(pair.Key, (TOut)Conversion.ConvertTo(pair.Value)); converted.ToList().CopyTo(array, arrayIndex); } public int Count { get { return toWrap.Count; } } public bool IsReadOnly { get { return toWrap.IsReadOnly; } } public bool Remove(KeyValuePair item) { return toWrap.Remove(new KeyValuePair(item.Key, (TIn)Conversion.ConvertTo(item.Value))); } public IEnumerator> GetEnumerator() { foreach (var pair in toWrap) { yield return new KeyValuePair(pair.Key, (TOut)Conversion.ConvertTo(pair.Value)); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }