mardi 7 août 2018

Invoke List of generic objects as parameter

I'm trying to iterate on all values in object and values in nested classes. I have a problem with Invoking with a list of generic elements.

Object of type System.Collections.Generic.List [System.Object] cannot be converted to type System.Collections.Generic.List [ConsoleApp.Class1].

public class Class1 {

    public string a { get; set; }
    public string b { get; set; }
}
public class Class2
{
    public string c { get; set; }
    public Class1 d { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        //test dataset
        List<Class2> testItem = new List<Class2>();
        List<Class1> tmp = new List<Class1>();
        testItem.Add(new Class2() { c = "1", d = new Class1() {a="1", b="2" } });
        testItem.Add(new Class2() { c = "1", d = new Class1() { a = "1", b = "2" } });
        int i = 0;
        NestedToString(testItem, ref i);
    }

    public static void NestedToString<T>(List<T> query, ref int iteratorStart)
    {
        var t = typeof(T);
        var Headings = t.GetProperties();
        for (int i = iteratorStart; i < Headings.Count(); i++)
        {
            if (Headings[i].PropertyType.FullName == "System.String")
            {
                Console.Write(iteratorStart.ToString() + " " + Headings[i]);
                var nested = query.Select(p => Headings[i].GetValue(p)).ToList();
                foreach (var item in nested) Console.Write(" - " + item);
                Console.WriteLine();
                iteratorStart++;
            }
            else
            {
                Type type = Type.GetType(Headings[i].PropertyType.FullName);
                var mi = typeof(Program);
                var met = mi.GetMethod("NestedToString");
                var genMet = met.MakeGenericMethod(type);
                var nested = query.Select(p => Headings[i].GetValue(p)).ToList();
                genMet.Invoke(null, new object[] { nested, i });
            }
        }
    }
}

This sample code just writes on console Iterator, property name, and values in a list. Writing values working fine, but invoke don't. Types are fine, but for some reason debugger interprets the object as List<object> instead of List<Class1>.





Aucun commentaire:

Enregistrer un commentaire