vendredi 22 juin 2018

How to use reflection to get all the variables in an object?

I'm currently using this code to get all the variables in an object and place the data in a Dictionary (the key is a variable name, the value is the variable's contents).

foreach (var property in PropertiesOfType<string>(propertiesJSON))
{
    dictionary.Add(property.Key, property.Value);
}

In this code, propertiesJSON is the object I need. Here's the PropertiesOfType method:

public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
    return from p in obj.GetType().GetProperties()
           where p.PropertyType == typeof(T)
           select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}

When I test my Dictionary for any data, there are no values (I used Visual Studio's debugging stuff to check, and my program also printed out all the data inside the Dictionary - which is of course, not there). Please tell me the mistake I'm doing here (I'm still learning to code, I'm 15 at the time of posting this).

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire