Just convert the object to dictionary. This answer has the method below that can serve well:
public static KeyValuePair<object, object> Cast<K, V>(this KeyValuePair<K, V> kvp)
{
return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
}
public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)
{
return (KeyValuePair<T, V>) obj;
}
public static KeyValuePair<object, object> CastFrom(Object obj)
{
var type = obj.GetType();
if (type.IsGenericType)
{
if (type == typeof (KeyValuePair<,>))
{
var key = type.GetProperty("Key");
var value = type.GetProperty("Value");
var keyObj = key.GetValue(obj, null);
var valueObj = value.GetValue(obj, null);
return new KeyValuePair<object, object>(keyObj, valueObj);
}
}
throw new ArgumentException(" ### -> public static KeyValuePair<object, object> CastFrom(Object obj) : Erro : argumento obj deve ser do tipo KeyValuePair<,>");
}
Use:
var dicionario = CastFrom(objeto);
Or even this answer, who opinionated it best to be an extension of any object:
public static class ObjectToDictionaryExtension
{
public static IDictionary<string, object> ToDictionary(this object source)
{
return source.ToDictionary<object>();
}
public static IDictionary<string, T> ToDictionary<T>(this object source)
{
if (source == null)
ThrowExceptionWhenSourceArgumentIsNull();
var dictionary = new Dictionary<string, T>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
AddPropertyToDictionary<T>(property, source, dictionary);
return dictionary;
}
private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
{
object value = property.GetValue(source);
if (IsOfType<T>(value))
dictionary.Add(property.Name, (T)value);
}
private static bool IsOfType<T>(object value)
{
return value is T;
}
private static void ThrowExceptionWhenSourceArgumentIsNull()
{
throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
}
}
Use:
var dicionario = objeto.ToDictionary();
Usa json then...
– David Schrammel
Explain a little better what you want. Is this? http://answall.com/a/90671/101
– Maniero
I rephrased @bigown, see if it’s a little clearer.
– Joao Paulo
Do you want to access both ways? Or do you want to access only from the top form?
– Maniero
Only the top shape, via string
– Joao Paulo
My understanding was that you want to string in the properties of an object, right? In this case I believe you have to use Reflection.
– MFedatto
I posted an answer using
Reflection
which allows you to use exactly as in your example. The object has properties with their respective types and can be read and written identifying them by string.– MFedatto