How do I convert a ConcurrentDictionary to a dictionary at runtime?

I know how to convert ConcurrentDictionary to dictionary.

And I know that I can use reflection to determine if a ConcurrentDictionary object contains.

But after I have determined that the object has a ConcurrentDictionary through reflection, how do I convert it to a dictionary at runtime? Or can I do this at all? He's going to change the definition of the class, right?

Edit: I should have made it clearer. I'll give an example:

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

        ......
    }

      

When I serialize an instance of this class, AVRO cannot serialize the ConcurrentDictionary. So I wondered if I could convert the ConcurrentDictionary to a regular dictionary at runtime. And it certainly changes the definition of a class. I'm just wondering if it can be done like this.

+3


source to share


1 answer


ConcurrentDictionary<TKey, TValue>

implements IDictionary<TKey, TValue>

, so anywhere you try to use a "dictionary" you can use an interface. For example:

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

      

You can call a method like this and you should be fine:

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

      

Alternatively, if you have a method that you want to use that requires a specific type Dictionary<TKey,TValue>

, you can use the Dictionary constructor that takes an existing IDictionary:

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

      

Then call it like this:



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

      

Just remember that calling this constructor is an operation O(n)

.

If you're trying to use reflection, you can determine that the object is a ConcurrentDictionary by examining the object's type at runtime via GetType()

:

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

      

But in this case, you can forget about the generic type parameters and just check the interface IDictionary

:

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

      

+3


source







All Articles