gpt4 book ai didi

c# - 处理多个 List 的通用方法

转载 作者:行者123 更新时间:2023-11-30 14:10:13 25 4
gpt4 key购买 nike

我有多个 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);

关于c# - 处理多个 List<Class> 的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25167771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com