C# 将IDictionary转换为泛型IDictionary的最佳方法

C# 将IDictionary转换为泛型IDictionary的最佳方法,c#,generics,C#,Generics,我有一个IDictionary字段,我想通过类型为IDictionary的属性公开该字段。转换非常困难,因为我不知道我能将IDictionary转换成什么 我最喜欢的是: IDictionary properties; protected virtual IDictionary<string, dynamic> Properties { get { return _properties.Keys.Cast<string>()

我有一个IDictionary字段,我想通过类型为
IDictionary
的属性公开该字段。转换非常困难,因为我不知道我能将IDictionary转换成什么

我最喜欢的是:

IDictionary properties;
protected virtual IDictionary<string, dynamic> Properties {
  get { 
        return _properties.Keys.Cast<string>()
              .ToDictionary(name=>name, name=> _properties[name] as dynamic); 
      }
    }
i词典属性;
受保护的虚拟IDictionary属性{
获取{
return _properties.Keys.Cast()
.ToDictionary(name=>name,name=>\u属性[name]为动态);
}
}

您需要使用KeyValuePair

myDictionary.Cast<KeyValuePair<Type1, Type2>>()
myDictionary.Cast()

如果
IDictionary
的基础类型未实现
IDictionary
,则无法强制转换对象句点。如果是这样,通过
(IDictionary)localVar进行简单的强制转换就足够了

如果不是,你可以做两件事:

  • IDictionary
    复制到您的泛型类型
  • 构建一个类,该类接受
    IDictionary
    作为依赖项,并实现所需的泛型
    IDictionary
    ,将调用从一个映射到另一个 编辑:您刚刚发布的示例代码将在每次调用字典时复制它!稍后我将用一些建议的代码再次编辑

    选项1

    您的示例代码方法作为复制数据的一种方法是可靠的,但是应该缓存副本,否则您将复制很多次。我建议您将实际的翻译代码放入一个单独的方法中,并在第一次使用它时从您的属性调用它。例如:

    private IDictionary dataLayerProperties; 
    private IDictionary<string, dynamic> translatedProperties = null;
    protected virtual IDictionary<string, dynamic> Properties
    {
        if(translatedProperties == null)
        {
            translatedProperties = TranslateDictionary(dataLayerProperties);        
        }  
        return translatedProperties;
    }
    
    public IDictionary<string, dynamic> TranslateDictionary(IDictionary values)
    {
        return values.Keys.Cast<string>().ToDictionary(key=>key, key => values[key] as dynamic);            
    }
    
    私有IDictionary数据层属性;
    私有IDictionary translatedProperties=null;
    受保护的虚拟IDictionary属性
    {
    if(translatedProperties==null)
    {
    translatedProperties=TranslateDictionary(dataLayerProperties);
    }  
    返回translatedProperties;
    }
    公共IDictionary TranslateDictionary(IDictionary值)
    {
    返回values.Keys.Cast().ToDictionary(key=>key,key=>values[key]为动态);
    }
    
    现在,这种方法有明显的缺点。。。如果需要刷新dataLayerProperties怎么办?您必须再次将translatedProperties设置为null,等等

    选项2

    这是我喜欢的方法

    public class TranslatedDictionary : IDictionary<string, dynamic>
    {
        private IDictionary Original = null;
    
        public TranslatedDictionary(IDictionary original)
        {
            Original = original;
        }
        public ICollection<string> Keys
        {
            get
            {
                return Original.Keys.Cast<string>().ToList();
            }
        }
    
        public dynamic this[string key]
        {
            get
            {
                return Original[key] as dynamic;
            }
            set
            {
                Original[key] = value;
            }
        }
        // and so forth, for each method of IDictionary<string, dynamic>
    }
    
    //elsewhere, using your original property and field names:
    Properties = new TranslatedDictionary(properties);
    
    公共类TranslatedDictionary:IDictionary
    {
    私有IDictionary Original=null;
    公共翻译词典(IDictionary原件)
    {
    原件=原件;
    }
    公共ICollection密钥
    {
    得到
    {
    返回原始的.Keys.Cast().ToList();
    }
    }
    公共动态此[字符串键]
    {
    得到
    {
    将原始[键]返回为动态;
    }
    设置
    {
    原始[键]=值;
    }
    }
    //依此类推,对于IDictionary的每个方法
    }
    //在其他地方,使用原始属性和字段名:
    属性=新的TranslatedDictionary(属性);
    

    现在,这种方法也有明显的缺点,最明显的是
    (在
    IDictionary
    上返回
    ICollection
    的值和任何其他内容都必须为每个调用返回一个新数组。但这仍然允许最灵活的方法,因为它确保数据始终是最新的。

    除非
    IDictionary
    实例的备份类型已经实现了
    IDictionary
    )>(如
    Dictionary
    )则强制转换对您没有帮助。
    Cast()
    方法仅用于返回
    IEnumerable
    值,而正常强制转换不是一个选项


    如果以
    IDictionary
    的形式提供数据很重要,那么为什么不从一开始就将其存储为
    字典呢?

    下面是顶部答案中建议的方法的完整实现。这太大了,无法作为注释

        using System;
        using System.Collections;
        using System.Collections.Generic;
        using System.Diagnostics.CodeAnalysis;
        using System.Linq;
    
        /// <summary>
        /// The casted dictionary.
        /// </summary>
        /// <typeparam name="TKey">
        /// The key type
        /// </typeparam>
        /// <typeparam name="TValue">
        /// The value type
        /// </typeparam>
        public class CastedDictionary<TKey, TValue> : IDictionary<TKey, TValue>
        {
            /// <summary>
            /// The original dictionary.
            /// </summary>
            private readonly IDictionary originalDictionary;
    
            /// <summary>
            /// The keys.
            /// </summary>
            private ICollection<TKey> keys;
    
            /// <summary>
            /// The values.
            /// </summary>
            private ICollection<TValue> values;
    
            /// <summary>
            /// Initializes a new instance of the <see cref="CastedDictionary{TKey,TValue}"/> class.
            /// </summary>
            /// <param name="original">
            /// The original.
            /// </param>
            public CastedDictionary(IDictionary original)
                : this()
            {
                if (original == null)
                {
                    throw new ArgumentNullException("original");
                }
    
                this.originalDictionary = original;
            }
    
            /// <summary>
            /// Prevents a default instance of the <see cref="CastedDictionary{TKey, TValue}"/> class from being created.
            /// </summary>
            [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1642:ConstructorSummaryDocumentationMustBeginWithStandardText", Justification = "Style Cop does not analyze private generic class constructor comments properly")]
            private CastedDictionary()
            {
            }
    
            /// <summary>
            /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
            /// </summary>
            /// <returns>
            /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
            /// </returns>
            public int Count
            {
                get
                {
                    return this.originalDictionary.Count;
                }
            }
    
            /// <summary>
            /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
            /// </summary>
            /// <returns>
            /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
            /// </returns>
            public bool IsReadOnly
            {
                get
                {
                    return this.originalDictionary.IsReadOnly;
                }
            }
    
            /// <summary>
            /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </summary>
            /// <returns>
            /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </returns>
            public ICollection<TKey> Keys
            {
                get
                {
                    return this.keys ?? (this.keys = this.originalDictionary.Keys.Cast<TKey>().ToList());
                }
            }
    
            /// <summary>
            /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </summary>
            /// <returns>
            /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </returns>
            public ICollection<TValue> Values
            {
                get
                {
                    return this.values ?? (this.values = this.originalDictionary.Values.Cast<TValue>().ToList());
                }
            }
    
            /// <summary>
            /// Gets or sets the element with the specified key.
            /// </summary>
            /// <returns>
            /// The element with the specified key.
            /// </returns>
            /// <param name="key">The key of the element to get or set.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
            public TValue this[TKey key]
            {
                get
                {
                    return (TValue)this.originalDictionary[key];
                }
    
                set
                {
                    this.originalDictionary[key] = value;
                }
            }
    
            /// <summary>
            /// Returns an enumerator that iterates through the collection.
            /// </summary>
            /// <returns>
            /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
            /// </returns>
            /// <filterpriority>1</filterpriority>
            public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
            {
                return this.originalDictionary.Cast<KeyValuePair<TKey, TValue>>().GetEnumerator();
            }
    
            /// <summary>
            /// Returns an enumerator that iterates through a collection.
            /// </summary>
            /// <returns>
            /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
            /// </returns>
            /// <filterpriority>2</filterpriority>
            IEnumerator IEnumerable.GetEnumerator()
            {
                return this.GetEnumerator();
            }
    
            /// <summary>
            /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
            /// </summary>
            /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
            public void Add(KeyValuePair<TKey, TValue> item)
            {
                this.originalDictionary.Add(item.Key, item.Value);
            }
    
            /// <summary>
            /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
            /// </summary>
            /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
            public void Clear()
            {
                this.originalDictionary.Clear();
            }
    
            /// <summary>
            /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
            /// </summary>
            /// <returns>
            /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
            /// </returns>
            /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
            public bool Contains(KeyValuePair<TKey, TValue> item)
            {
                return this.originalDictionary.Contains(item.Key) && EqualityComparer<TValue>.Default.Equals(this[item.Key], item.Value);
            }
    
            /// <summary>
            /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
            /// </summary>
            /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception>
            public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
            {
                this.originalDictionary.CopyTo(array, arrayIndex);
            }
    
            /// <summary>
            /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
            /// </summary>
            /// <returns>
            /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
            /// </returns>
            /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
            public bool Remove(KeyValuePair<TKey, TValue> item)
            {
                if (this.Contains(item))
                {
                    this.originalDictionary.Remove(item.Key);
                    return true;
                }
    
                return false;
            }
    
            /// <summary>
            /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
            /// </summary>
            /// <returns>
            /// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
            /// </returns>
            /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
            public bool ContainsKey(TKey key)
            {
                return this.originalDictionary.Contains(key);
            }
    
            /// <summary>
            /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </summary>
            /// <param name="key">The object to use as the key of the element to add.</param><param name="value">The object to use as the value of the element to add.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
            public void Add(TKey key, TValue value)
            {
                this.originalDictionary.Add(key, value);
            }
    
            /// <summary>
            /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </summary>
            /// <returns>
            /// true if the element is successfully removed; otherwise, false.  This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
            /// </returns>
            /// <param name="key">The key of the element to remove.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
            public bool Remove(TKey key)
            {
                if (this.ContainsKey(key))
                {
                    this.originalDictionary.Remove(key);
                    return true;
                }
    
                return false;
            }
    
            /// <summary>
            /// Gets the value associated with the specified key.
            /// </summary>
            /// <returns>
            /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
            /// </returns>
            /// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
            public bool TryGetValue(TKey key, out TValue value)
            {
    // ReSharper disable CompareNonConstrainedGenericWithNull
                if (typeof(TKey).IsValueType == false && key == null)
    // ReSharper restore CompareNonConstrainedGenericWithNull
                {
                    throw new ArgumentNullException("key");
                }
    
                if (this.ContainsKey(key))
                {
                    value = this[key];
                    return true;
                }
    
                value = default(TValue);
                return false;
            }
        }
    
    使用系统;
    使用系统集合;
    使用System.Collections.Generic;
    使用System.Diagnostics.CodeAnalysis;
    使用System.Linq;
    /// 
    ///铸造词典。
    /// 
    /// 
    ///钥匙类型
    /// 
    /// 
    ///值类型
    /// 
    公共类CastedDictionary:IDictionary
    {
    /// 
    ///原版词典。
    /// 
    私人只读词典原件;
    /// 
    ///钥匙。
    /// 
    私有ICollection密钥;
    /// 
    ///价值观。
    /// 
    私有ICollection值;
    /// 
    ///初始化类的新实例。
    /// 
    /// 
    ///原著。
    /// 
    公共词典(IDictionary原件)
    :此()
    {
    如果(原始==null)
    {
    抛出新的ArgumentNullException(“原始”);
    }
    this.originalDictionary=原件;
    }
    /// 
    ///阻止创建类的默认实例。
    /// 
    [SuppressMessage(“StyleCop.CSharp.DocumentationRules”、“SA1642:ConstructorSummaryDocumentationMustBeginWithStandardText”、justify=“StyleCop未正确分析私有泛型类构造函数注释”)]
    专用词典
    {
    }
    /// 
    ///获取中包含的元素数。
    /// 
    /// 
    ///中包含的元素数。
    /// 
    公共整数计数
    {
    得到
    {
    返回this.originalDictionary.Count;
    }
    }
    /// 
    ///获取一个值,该值指示是否为只读。
    /// 
    /// 
    ///如果为只读,则为true;否则为false。
    /// 
    公共图书馆是只读的
    {
    得到
    {
    返回此.originalDictionary.IsReadOnly;
    }