vendredi 11 septembre 2015

.Net Reflection calling a function with a generic parameter - How to pass the type to the function

Hy, this is my first question here! I'm really struggling with these code bellow:

I Have these class:

public class Home {
    public List<Parametro> Parametro { get; set; }
}

I also ave a function with this specs:

public static List<T> DataTableMapToList<T>(DataTable dtb)
    { ... }

In another class when I need call these function, I need to pass the type of the my class but I'm in a reflection properties loop:

public void Initialize(ref object retObject)
    {
        using (var db = this)
        {

            db.Database.Initialize(force: false);

            var cmd = db.Database.Connection.CreateCommand();
            cmd.CommandText = sStoredProcedure;

            try
            {
                // Run the sproc
                db.Database.Connection.Open();
                DbDataReader reader = cmd.ExecuteReader();

                DataSet ds = new DataSet();
                ds.EnforceConstraints = false;
                ds.Load(reader, LoadOption.OverwriteChanges, sTables);

                var propertys = GetGenericListProperties(retObject);

                foreach (DataTable table in ds.Tables) {

                    foreach (var info in propertys)
                    {

                        if (info.Name == table.TableName)
                        {

                            Type myObjectType = info.PropertyType;

                            // Create an instance of the list
                            var list = Activator.CreateInstance(myObjectType);

                            var list2 = DataTableMapToList<???>(table).ToList();
                            //Where the variable myObjectType is the TYPE of the class where I need to pass on the ??? marker

                            info.SetValue(retObject, list, null);

                        }

                    }

                }

            }
            finally
            {
                db.Database.Connection.Close();
            }

        }

    } 

I've tried everything:

Pass as object and try convert after (I got an error of IConverter must be implemented);

Tried to put all my code - just for test - of the DataTableMapToList() and even so I got error of object conversion;

Force send list for my final variable but I have converter error again.;

I don´t know if I was clear enough about what I really need but I'm spend about 4 hours looking for a solution until know.

I appreciate any kind of help here!

Tks in advance!





Aucun commentaire:

Enregistrer un commentaire