【问题标题】:how to convert ConcurrentDictionary to Dictionary at runtime?如何在运行时将 ConcurrentDictionary 转换为 Dictionary?
【发布时间】:2015-04-29 05:22:22
【问题描述】:

我知道如何将 ConcurrentDictionary 转换为 Dictionary。

而且我知道我可以使用反射来确定对象是否包含 ConcurrentDictionary。

但是当我通过反射确定一个对象确实有一个 ConcurrentDictionary 之后,我如何在运行时将它转换为 Dictionary 呢?或者我可以做到吗?它会改变类的定义,对吧?

编辑:我应该说得更清楚。我举个例子:

    [Serializable]
    [DataContract]
    public class CacheItem
    {
        [DataMember]
        private ConcurrentDictionary<string, CacheItemEntity> _cacheItemDictionary = new ConcurrentDictionary<string, CacheItemEntity>();

        ......
    }

当我序列化此类的实例时,AVRO 无法序列化 ConcurrentDictionary。所以我想知道我是否可以在运行时将 ConcurrentDictionary 转换为普通字典。这肯定会改变类的定义。我只是想知道是否可以这样做。

【问题讨论】:

  • 想要转换类型的动机是什么?
  • @jdphenix,能够通过 microsoft AVRO 库序列化包含 ConcurrentDictionary 的对象。
  • var newDictionary = yourConcurrentDictionary.ToDictionary(kvp =&gt;vp.Key, kvp =&gt; kvp.Value);
  • var dictionary = new Dictionary&lt;TKey, TValue&gt;(concurrentDictionary);?
  • 你的问题很混乱,因为你说你知道怎么做A,你知道怎么做B,但是你想知道怎么做B然后A。问题是实际上由于使用反射,您在编译时不知道类型参数? “更改类的定义”是什么意思-您是否要更改字段本身的类型?如果你能把它说得更清楚,那真的很有帮助......

标签: c#


【解决方案1】:

ConcurrentDictionary&lt;TKey, TValue&gt; 实现了IDictionary&lt;TKey, TValue&gt;,因此在您尝试使用“字典”的任何地方,您都可以使用该接口。例如:

void ConsumeIDictionary(IDictionary dic)
{
   //perform work on a dictionary, regardless of the concrete type
}

你可以这样调用方法,就可以了:

ConsumeIDictionary(new ConcurrentDictionary<int,int>());

或者,如果您想使用需要具体 Dictionary&lt;TKey,TValue&gt; 类型的方法,则可以使用采用现有 IDictionary 的 Dictionary 构造函数:

void ConsumeDictionary<K,V>(Dictionary<K,V> dic)
{
   //perform work on a concrete Dictionary
}

然后这样称呼它:

ConsumeDictionary(
   new Dictionary(
       new ConcurrentDictionary<int,int>()));

请注意,调用此构造函数是 O(n) 操作。

如果您尝试使用反射,您可以通过GetType() 在运行时检查对象的类型来确定对象是 ConcurrentDictionary:

bool IsConcurrentDictionary<k, v>(obj o)
{
    return o.GetType() == typeof(ConcurrentDictionary<k,v>);
}

但在这种情况下,您可能想忘记泛型类型参数,只检查IDictionary 接口:

bool IsDictionary(obj o)
{
    return o is IDictionary;
}

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 2015-01-19
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多