类型参数的约束和错误 "cannot implicitly convert type"

Constraints on Type Parameters and error "cannot implicitly convert type"

我正在做一个项目,我对转换类型有疑问。

问题:

Cannot implicitly convert type 'ConsoleApplication2.Imp.StorageImp' to 'ConsoleApplication2.Storage(ConsoleApplication2.Item)

我的简单代码:

public interface IItem
{
    void Add();
}

public abstract class Item : IItem
{
    public abstract void Add();
}

public class ItemImp : Item
{
    public override void Add()
    {
        throw new NotImplementedException();
    }
}

public interface IStorage<T> where T : Item
{
    List<T> Get(); 
    bool Add(T item);
}

public abstract class Storage<T> : IStorage<T> where T : Item
{
    public abstract bool Add(T item);
    public abstract List<T> Get();
}

public class StorageImp : Storage<ItemImp>
{
    public override bool Add(ItemImp item)
    {
        throw new NotImplementedException();
    }

    public override List<ItemImp> Get()
    {
        throw new NotImplementedException();
    }
}

convert 的问题代码(我尝试将实现转换为基础 class):

class Program
{
    static void Main(string[] args)
    {
        Storage<Item> storage = new StorageImp();
    }
}

请帮助我。

编译器报告错误,因为 Storage<Item> 不是 StorageImp 的基础 class。相反 Storage<ItemImp>StorageImp 的基础 class。

所以替换

Storage<Item> storage = new StorageImp();

Storage<ItemImp> storage = new StorageImp();

更新

如果你想从 class "ItemImp" 的实现中抽象出来,那么你需要使 StorageImp 通用,如下所示:

class Program
{
    static void Main(string[] args)
    {
        Storage<Item> storage = new StorageImp<Item>();
    }
}



public interface IItem
{
    void Add();
}

public abstract class Item : IItem
{
    public abstract void Add();
}

public class ItemImp : Item
{
    public override void Add()
    {
        throw new NotImplementedException();
    }
}

public interface IStorage<T> where T : Item
{
    List<T> Get();
    bool Add(T item);
}

public abstract class Storage<T> : IStorage<T> where T : Item
{
    public abstract bool Add(T item);
    public abstract List<T> Get();
}

public class StorageImp<T> : Storage<T> where T: Item
{
    public override bool Add(T item)
    {
        throw new NotImplementedException();
    }

    public override List<T> Get()
    {
        throw new NotImplementedException();
    }
}