esto debería funcionar:
para números, cadenas, fecha, etc .:
public static void MyMethod(object obj)
{
if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
{
IDictionary idict = (IDictionary)obj;
Dictionary<string, string> newDict = new Dictionary<string, string>();
foreach (object key in idict.Keys)
{
newDict.Add(key.ToString(), idict[key].ToString());
}
}
else
{
// My object is not a dictionary
}
}
si su diccionario también contiene algunos otros objetos:
public static void MyMethod(object obj)
{
if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
{
IDictionary idict = (IDictionary)obj;
Dictionary<string, string> newDict = new Dictionary<string, string>();
foreach (object key in idict.Keys)
{
newDict.Add(objToString(key), objToString(idict[key]));
}
}
else
{
// My object is not a dictionary
}
}
private static string objToString(object obj)
{
string str = "";
if (obj.GetType().FullName == "System.String")
{
str = (string)obj;
}
else if (obj.GetType().FullName == "test.Testclass")
{
TestClass c = (TestClass)obj;
str = c.Info;
}
return str;
}
Se comprueba que su objeto es una 'IDictionary'. Entonces lanzar a esa interfaz, como '(IDictionary) obj', tendrá éxito. Sin embargo, hay muchos otros 'Idictionary' que' Dictionary '. Por lo tanto, es mejor que pruebe el mismo tipo al que desea lanzar. Estoy de acuerdo con Nikhil (que responde) que quiere usar 'como 'en este caso. Puedo proporcionar detalles si es necesario. –
En general, considere las respuestas aquí: http://stackoverflow.com/questions/3481923/in-c-sharp-convert-anonymous-type-into-key-value-array (por ejemplo, 'RouteValueDictionary') –