說我有兩個集合即列表< 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