mercredi 10 février 2016

Loop through and assign values to class properties using PropertyInfo[]

I'm trying to automatically assign string values, from an array of strings, to a classes properties using a propertyinfo array.

Class Car
{
    public string wheels, doors, windows;
    PropertyInfo[] props = typeof(Car).GetProperties();
    public Car(string[] values)
    {
        int index=0;
        foreach(PropertyInfo pi in props)
        {
            pi.SetValue(pi.Name, values[index], null);
            //pi.SetValue(pi.Name, values[index]);
        }
    }
}

I get an error saying "Object does not match target type." I'm sure what I'm missing after seeing some other examples on Stack or other message boards.





Aucun commentaire:

Enregistrer un commentaire