说我有两个集合即列表< PersonOld>和List < PersonNew> as下。使用通用功能将一个集合的内容复制到另一个
private List<PersonOld> GetOldPersonRecord()
{
var sourceList = new List<PersonOld>();
for (int i = 1; i <= 10; i++)
sourceList.Add(new PersonOld { PersonId = i, PersonName = "Name" + i.ToString() });
return sourceList;
}
需要的是填充列表< PersonNew>与清单< PersonOld>的值。
它需要是通用的..means给定的任何源收集和目的地的效用函数,它需要从源填充目标集合。
我想
public List<T2> Fill<T1, T2>(List<T1> Source, List<T2> Destination)
{
Type type1 = typeof(T1);
var type1List = type1.GetProperties();
Type type2 = typeof(T2);
var type2List = type2.GetProperties();
//determine the underlying type the List<> contains
Type elementType = type1.GetGenericArguments()[0];
foreach (object record in Source)
{
int i = 0;
object[] fieldValues = new object[Destination.Count];
foreach (PropertyInfo prop in Destination)
{
MemberInfo mi = elementType.GetMember(prop.Name)[0];
if (mi.MemberType == MemberTypes.Property)
{
PropertyInfo pi = mi as PropertyInfo;
fieldValues[i] = pi.GetValue(record, null);
}
else if (mi.MemberType == MemberTypes.Field)
{
FieldInfo fi = mi as FieldInfo;
fieldValues[i] = fi.GetValue(record);
}
i++;
}
//Destination..Add(fieldValues);
}
}
和调用
var source = GetOldPersonRecord();
var result = Utility.Fill(source, new List<PersonNew>());
但没有luck..please帮助
的实体是为下
PersonNew
public class PersonNew
{
public int PersonId { get; set; }
public string PersonName { get; set; }
}
PersonOld
public class PersonOld
{
public int PersonId { get; set; }
public string PersonName { get; set; }
}
我可能要使用反射...
在此先感谢
是使用 “动态” 的一个可行的选择? – 2012-01-13 08:25:08