mercredi 7 juin 2017

Reflection Setting values of a class

I am trying to build an extension to populate an object with values from a SQLDataReader.

The code I have so far is

public static T RetunObject<T>(this Type source, SqlDataReader dr)
    {
        Type type = source.GetType();
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            property.SetValue(property, dr[property.Name]);
            type.GetProperty(property.Name).SetValue(type, dr[property.Name]);
        }

        return type.Cast<T>();
    }

One thing for sure is the last line is not right and not exactly sure if there is a way for this to work at this point.

The goal results would be to use the code like

MyClass myclass = new MyClass();
var results = myclass.ReturnObject(myDataReader);

Reflection has never been my strong suit. so I am pretty sure I am pretty far off.





Aucun commentaire:

Enregistrer un commentaire