C # Casting Dictionary

I have this function:

void WriteMap(object value)  
{  
    IDictionary<string, object> vv = (IDictionary<string, object>)value;  
    foreach (KeyValuePair<string, object> obj in vv)  
    {  
        (write key)  
        (write value)  
    }  
}  

This works if the value really has a type IDictionary<string, object>, but it can be anything:
  IDictionary<string, int>  IDictionary<string, MyClass>  IDictionary<string, string[]> etc.

A cast throws an exception at run time. The function does not change the container, it only prints keys and values. Any ideas on how I can make this work? Any help would be greatly appreciated.

Thank!

+3
source share
4 answers

Add a generic type to your method that matches the type of values ​​in the dictionary:

void WriteMap<T>(IDictionary<string, T> dict)
{
    foreach (KeyValuePair<string, T> in dict)
    {
        // write key
        // write value
    }
}

This has the advantage of eliminating the cast. If you need to pass the dictionary as an object for some reason, just add it to IDictionary.

+3
source

Pass it in non-generic IDictionary:

IDictionary vv = (IDictionary)value;  
foreach (var key in vv.Keys)  
{  
    var value = vv[key];
}  
+1

-, object , IDictionary? , , .

, IDictionary 'es ( ..), . , , : IDictionary, ? , object .

:

void WriteMap<TKey, TValue>(IDictionary<TKey, TValue> dict)  
{  
    foreach (var kv in dict) // kv is KeyValuePair<TKey, TValue>
    {  
        // (write key)  
        // (write value)  
    }  
}  

TKey TValue, , . where .

, string, :

void WriteMap<TValue>(IDictionary<string, TValue> dict)  
{  
    foreach (var kv in dict) // kv is KeyValuePair<string, TValue>
    {  
        // (write key)  
        // (write value)  
    }  
}  

One of the drawbacks of this method is that the compiler must be able to infer type TValueat compile time. If this is not known or the types of values ​​may be different, it may make sense to use IDictionary instead:

void WriteMap(IDictionary dict)  
{  
    foreach (var kv in dict) // kv is DictionaryEntry
    {  
        // (write key)  
        // (write value)  
    }  
}  

Please note that in this case the key is not limited string.

+1
source

If you want to print the values, you can use the non-general IDictionary interface :

void WriteMap(object value)  
{  
    IDictionary vv = (IDictionary)value;  
    foreach (DictionaryEntry de in vv)  
    {  
        object key = de.Key;
        object value = de.Value;
        (write key)  
        (write value)  
    }  
}  
0
source

Source: https://habr.com/ru/post/1794192/


All Articles