类型参数和错误的约束“不能隐式转换类型”

问题描述:

我正在一个项目上工作,我有一个关于转换类型的问题。类型参数和错误的约束“不能隐式转换类型”

问题:

无法隐式转换类型 'ConsoleApplication2.Imp.StorageImp' 到 “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(); 
    } 
} 

转换问题代码(我试图将实现转换为基类):

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

请帮帮我。

+1

您无法将派生类转换为其基类,但您可以将其转换为 – 2015-11-04 04:08:30

+0

为什么我无法将派生类转换为基类? –

+0

为什么你在这里有这么多的抽象层?由于抽象基类没有真正提供任何基本功能,你只是混淆了类型系统。如果你的实际实现遵循你的例子,我会抛弃抽象类,让具体的实现直接实现接口。 –

编译器报告错误,因为Storage<Item>不是基类StorageImp。而不是Storage<ItemImp>StorageImp的基类。

所以更换

Storage<Item> storage = new StorageImp(); 

Storage<ItemImp> storage = new StorageImp(); 

更新

如果你想从类 “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(); 
    } 
} 
+0

它的工作原理,但我需要从类“ItemImp”的实现抽象。它可能是别的吗? –

+0

@AntonGorinenko然后,您需要使'StorageImp'类型也具有通用的约束,即通用类型需要为'Item' –

+0

StorageImp类应该与基类Item的特定实现一起工作。例如,ItemImp ... –