c# – 处理多个List的通用方法
发布时间:2020-12-16 02:02:46 所属栏目:百科 来源:网络整理
导读:我有多个void方法基本上做同样的事情: public void SaveToDb1(ListClass1 class1ItemList)public void SaveToDb2(ListClass2 class2ItemList) 等……等等…… 在每种方法中,我对每个项目列表执行相同的操作. foreach (Class1 item in class1ItemList){ //do
我有多个void方法基本上做同样的事情:
public void SaveToDb1(List<Class1> class1ItemList) public void SaveToDb2(List<Class2> class2ItemList) 等……等等…… 在每种方法中,我对每个项目列表执行相同的操作. foreach (Class1 item in class1ItemList) { //do work } 由于Class1!= Class2,但它们执行相同的工作,我如何制作一个处理任何类/属性组合的通用方法? 我想我得到了答案(谢谢!)……但是为了清晰起见,这里是做工作部分. 编辑: //get the type to iterate over their properties Type _type = typeof(Class1); DataTable dt = new DataTable(); //add columns to datatable for each property foreach (PropertyInfo pInfo in _type.GetProperties()) { dt.Columns.Add(new DataColumn(pInfo.Name,pInfo.PropertyType)); } foreach (Class1 item in class1ItemList) { DataRow newRow = dt.NewRow(); //copy property to data row foreach (PropertyInfo pInfo in _type.GetProperties()) { //form the row newRow[pInfo.Name] = pInfo.GetValue(item,null); } //add the row to the datatable dt.Rows.Add(newRow); } 解决方法
试试这个
public void SaveToDB1<T>(List<T> class1ItemList) where T:class { foreach(T item in class1ItemList) { //do something. } } 调用方法: List<Class1> list=new List<Class1>(); SaveToDB1<Class1>(list); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |