繁体   English   中英

将通用对象列表转换为非通用类型列表

[英]Convert generic object list to non-generic type list

我想一个转换ListSystem.Object对象添加到List强类型的对象。

这是我得到的错误:

类型'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);
            }

这是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);
                    }
                }
            }

如果您知道所有值都是列表中的必需类型:

List<Object> objects;
List<Cat> cats = objects.Cast<Cat>().ToList();

如果不是所有的值都是该类型,那么您想清除那些不是的值:

List<Object> objects;
List<Cat> cats = objects.OfType<Cat>().ToList();

两者都需要LINQ。

如果直到运行时才知道类型,则必须使用反射。

如何通过反射调用泛型方法

好的,我实现了目标。 全部归功于动态变量。 我对使用.NET能够做到这一点印象深刻。 你怎么看? 谢谢 :)

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

Type genericListType = typeof(List<>).MakeGenericType(t);

object coll = Activator.CreateInstance(genericListType);

dynamic objectColl = Convert.ChangeType(coll, coll.GetType());

dynamic d = Convert.ChangeType(obj, obj.GetType());

objectColl.Add(d);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM