派生对象列表

本文关键字:列表 对象 派生 | 更新日期: 2023-09-27 18:11:22

我需要在我的应用程序中保留一个已创建对象的列表。我有一个抽象对象和一些派生类。我想保留一个已创建对象的列表,以避免不必要地创建新对象。我尝试用下面的代码来做这件事,其中T是从AbstractMapper派生出来的。但是得到错误

无法将类型"AbstractMapper"转换为"T"

添加到列表

protected List<AbstractMapper> Mappers = new List<AbstractMapper>()
public AbstractMapper Mapper<T>()
    {
        foreach (var mapper in Mappers)
        {
            if (mapper.Type == typeof (T).Name)
            {
                return mapper;
            }
        }
        var newMapper = GetClass<T>("mapper");
        Mappers.Add((AbstractMapper)newMapper);
        return (AbstractMapper)newMapper;
    }

派生对象列表

你似乎缺乏泛型约束来帮助编译器确保你的代码是类型安全的

public AbstractMapper Mapper<T>()
    where T : AbstractMapper

这种方式将使用限制为仅从AbstractMapper继承的T

无论如何,编译器应该警告您T不能转换为AbstractMapper,而不是相反。

您确定没有看到以下错误吗?

无法将类型"T"转换为"AbstractMapper"

问题是编译器不能保证你的泛型类型参数TAbstractMapper的子类型。您应该添加泛型类型约束:

public AbstractMapper Mapper<T>() where T : AbstractMapper

那么你可以考虑返回T而不是AbstractMapper

您也可以考虑使用Dictionary而不是List,其中密钥是typeof(T)。如果需要派生类型的对象池,还可以使用泛型类型的静态字段:

public static class MapperProvider<T> where T : AbstractMapper
{
    public static T Instance = GetType<T>(); //static initialization
}

从泛型类型定义MapperProvider<T>创建的每个泛型类型将具有不同的静态Instance字段,然后从Mapper<T>查找适当的实例就像返回MapperProvider<T>.Instance一样简单。