【发布时间】:2015-06-04 06:15:27
【问题描述】:
我正在尝试将 System.Object 对象的 List 转换为强类型对象的 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);
}
}
}
【问题讨论】:
-
你能发布你的尝试吗?
-
你能添加你使用的代码(或者至少是暗示强类型列表的sn-ps
-
同时使用反射和泛型通常意味着你不应该使用either。
标签: c# object generics reflection