将泛型对象列表转换为非泛型类型列表

dec*_*cks 1 c# generics reflection object

我正在尝试将 a ListofSystem.Object对象转换为 a Listof 强类型对象。

这是我得到的错误:

“System.Collections.Generic.List`1[System.Object]”类型的对象无法转换为“System.Collections.Generic.List`1[TestApp.Tsc_Mrc_Step]”类型。

目的是因为我正在为我的项目编写一个业务数据层,您所要做的就是将您的类和属性命名为与数据库中的实体相同的名称,并且数据层将自动填充引用的表作为在班级。

业务数据层使用反射、泛型和对象来处理所有这些。

下面是我尝试将对象列表放入已知类型列表的代码。问题是,对象是已知类型,但我将其作为对象传递....如何在不知道它是什么的情况下将其转换为已知类型?

            bool isCoollection = false;
            Type t = GetTypeInsideOfObjectByTypeName(o, tableName, out isCoollection);

            List<object> objectColl = new List<object>();

            object obj = Activator.CreateInstance(t);
            if (obj != null)
            {
                PropertyInfo[] objectProps = obj.GetType().GetProperties();
                foreach (PropertyInfo op in objectProps)
                {
                    if (HasColumn(reader, op.Name))
                    {
                        op.SetValue(obj, reader[op.Name]);
                    }
                }

                if (isCoollection)
                {
                    objectColl.Add(obj);
                }
            }

            if (isCoollection)
            {
                IEnumerable<object> objs = objectColl.AsEnumerable();

                SetObject(o, objs);
            }
            else
            {
                SetObject(o, obj);
            }
Run Code Online (Sandbox Code Playgroud)

这是 SetObject:

            public static void SetObject(object parentObject, object newObject)
            {
                PropertyInfo[] props = parentObject.GetType().GetProperties();
                string typeName = newObject.GetType().Name;
                foreach (PropertyInfo pi in props)
                {
                    if (pi.PropertyType.Name.ToLower() == typeName.ToLower())
                    {
                        pi.SetValue(parentObject, newObject);
                    }
                    else if (!pi.PropertyType.IsValueType && !pi.PropertyType.Namespace.ToLower().Contains("system"))
                    {
                        SetObject(pi.GetValue(parentObject), newObject);
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

Kyl*_*e W 5

If you know all of the values are of the required type in a list:

List<Object> objects;
List<Cat> cats = objects.Cast<Cat>().ToList();
Run Code Online (Sandbox Code Playgroud)

If not all the values are of the type, and you want to weed out the ones that aren't:

List<Object> objects;
List<Cat> cats = objects.OfType<Cat>().ToList();
Run Code Online (Sandbox Code Playgroud)

Both require LINQ.

If you don't know the type until runtime, you have to use reflection.

How to call a generic method through reflection