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

标签 c# class generics propertyinfo

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

相关文章:

c# - 当我运行 WPF MVVM 应用程序时,显示主窗口的两个实例

c# - 填充依赖于内容页的母版页控件的最佳方法是什么?

c++ - 编译崩溃 - 在另一个成员函数中使用一个成员函数

symfony - 如何在Symfony 4中获得有效的类(class)?

java - 将继承的变量强制转换为子类

c# - 如何查找 PDF 文档的条形码

c# - 缺少可移植类库 WebResponse StatusCode

PHP:在类构造函数中使用 file_get_contents() 是一种不好的做法吗?

android - 泛型类型和多态性

java - 如何调用不同泛型类型的方法