generics - C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it? -


i'm trying write dump() method linqpad equivalent iin c# own amusment. i'm moving java c# , exercise rather business requirement. i've got working except dumping dictionary.

the problem keyvaluepair value type. other value types call tostring method insufficient keyvaluepair may contain enumerables , other objects undesirable tostring methods. need work out if it's keyvaluepair , cast it. in java use wildcard generics don't know equivalent in c#.

your quest, given object o, determine if it's keyvaluepair , call print on key , value.

print(object o) {    ... } 

thanks!

if don't know types stored in keyvaluepair need exercise bit of reflection code.

let's @ needed:

first, let's ensure value isn't null:

if (value != null) { 

then, let's ensure value generic:

    type valuetype = value.gettype();     if (valuetype.isgenerictype)     { 

then, extract generic type definition, keyvaluepair<,>:

        type basetype = valuetype.getgenerictypedefinition();         if (basetype == typeof(keyvaluepair<,>))         { 

then extract types of values in it:

            type[] argtypes = basetype.getgenericarguments(); 

final code:

if (value != null) {     type valuetype = value.gettype();     if (valuetype.isgenerictype)     {         type basetype = valuetype.getgenerictypedefinition();         if (basetype == typeof(keyvaluepair<,>))         {             type[] argtypes = basetype.getgenericarguments();             // process values         }     } } 

if you've discovered object indeed contain keyvaluepair<tkey,tvalue> can extract actual key , value this:

object kvpkey = valuetype.getproperty("key").getvalue(value, null); object kvpvalue = valuetype.getproperty("value").getvalue(value, null); 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -