Object 反射 List

时间:2022-06-07 21:31:06
 public static object DeserializeModel<T>(object dataModel)
{
Type type = typeof(T);
Object entity = Activator.CreateInstance(type);
Type data = dataModel.GetType();
if (data.Name.Contains("List"))
{
List<T> listCall = new List<T>();
//需要被转换的对象
IEnumerable<object> list = dataModel as IEnumerable<object>;
foreach (var sourceModel in list)
{
entity = Activator.CreateInstance(type);
//循环需要被反对对象的字段
foreach (var item in type.GetProperties())
{
var source = sourceModel.GetType();
if (source.GetProperty(item.Name) != null)
{
var val = source.GetProperty(item.Name).GetValue(sourceModel, null);
item.SetValue(entity, val);
} }
listCall.Add((T)entity);
}
return listCall; }
else
{
foreach (var item in type.GetProperties())
{
if (data.GetProperty(item.Name) != null)
{
var val = data.GetProperty(item.Name).GetValue(dataModel, null);
item.SetValue(entity, val);
} }
return (T)entity;
}
}

根据T类型将传入进来的Object对象进行反射,有待完善记录一下