创建一个泛型方法来修改未知类型的引用列表

Create a generic method to modify a reference list of unknown type

我有几个数据库脚本都包含自己类型的列表。

像下面的例子:

public class FooDatabase()
{
    public List<Bar> myCollection;
}

比我有更多相同格式的数据库:

public class OtherDatabase()
{
    public List<OtherBar> myCollection;
}

List 中的项目总是有一个 int ID,不管它们是什么类型。

现在我正在寻求实现一个通用方法,该方法采用 ref 集合并对其执行一些操作。问题是如果我给他们一个接口,我就不能修改 ref 集合。

public static void FillDatabase<T>(ref List<T> collection, string folderName)
{
    collection = new List<T>();

    List<T> foundItems = Resources.LoadAll(folderName, typeof(T)).ToList();

    // I need to make changes to the ID field regardless of which collection and type is passed in
    // Can't do the following, because it doesn't know it has the field ID
    foundItems.Find(item => item.ID == 0);

}

我试图将列表更改为 List<IDatabaseEntry> 类型之一,其中 IDatabaseEntry 包含 ID 字段并让每个数据库中的每个 class 实现该接口。问题是我无法修改原始集合,因为原始集合不是 List<IDatabaseEntry>

类型

感谢任何指向正确方向的帮助。

public static void FillDatabase<T>(ref List<T> collection, string folderName) where T : IDatabaseEntry
{
    collection = new List<T>();

    List<T> foundItems = Resources.LoadAll(folderName, typeof(T)).ToList();

    // I need to make changes to the ID field regardless of which collection and type is passed in
    // Can't do the following, because it doesn't know it has the field ID
    foundItems.Find(item => item.ID == 0);

}

应该可以解决您的问题。

另一种方法 - 如果您的类型具有不同的 ID 类型或属性,您可以传递 Func 返回 ID 作为参数之一:

public static void FillDatabase<T, TKey>(ref List<T> collection, 
    string folderName, 
    Func<T, TKey> idGetter)
{
    collection = new List<T>();

    List<T> foundItems = Resources.LoadAll(folderName, typeof(T)).ToList();

    foundItems.Find(item => idGetter(item) == default(TKey));
}