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/

相关文章:

generics - Kotlin 编译器的类型推断无法选择调用哪个方法(泛型有歧义)

java - 类型删除 - 泛型 - 在预期的地方获取 ClassCastException

c# - 使用 MiniProfiler For MVC 时如何限制显示的项目

c# - 扩展 ArrayList 和实现 IEnumerable - 有更好的方法吗?

c++ - 类和更新数据

c++ - 如何比较类中的两个对象(调用对象和参数)?

c# - 通用扩展方法 : Type argument cannot be inferred from the usage

c# - htmlagilitypack 选择节点返回空

c# - 如何在 3d 空间 C# 中给定三个点找到圆的半径

c# - 交换类实例数组中的值