SetValue映射属性赋值的问题
本帖最后由 will_stier 于 2013-07-07 00:29:09 编辑
public static T CopyToT<S>(S source) where S:new()
{
T result = new T();
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
PropertyInfo[] sProperties = typeof(S).GetProperties();
foreach (var item in properties)
{
try
{
//if source has this Property
bool flag = false;
foreach (var q in sProperties)
{
if (q.ToString() == item.ToString())
{
flag = true;
}
}
if (flag)
{
//set value for this Property
item.SetValue(result,item.GetValue(source,null),null);
}
}
catch
{
continue;
}
}
return result;
}
public static List<Student> GetStudentsByClassName(string className)
{
SPMEntities db = new SPMEntities();
var query = db.GetStudentByClassName(className);
List<Student> list = new List<Student>();
foreach (var item in query)
{
//copy item value to a student object;
list.Add(ConvertHelper<Student>.CopyToT(item));
}
return list;
}