我试图在我的 C# 项目中实现一个接口(interface)继承系统,但我无法让它工作。
这是一个简化的版本:
public interface BaseInterface {}
public abstract class AbstractClass<T> where T : BaseInterface {}
public interface ChildInterface : BaseInterface {}
public class ConcreteClass : AbstractClass<ChildInterface> {}
我想按如下方式使用它:
AbstractClass<BaseInterface> c = new ConcreteClass();
最后一行代码出现以下错误:
Cannot implicitly convert type 'ConcreteClass' to 'AbstractClass<BaseInterface>'
为什么无法转换?
最佳答案
让我们尝试一下您的类型并给它们起不同的名字。
public interface IFruit { }
public abstract class BowlOf<Fruit> where Fruit : IFruit
{
public void Add(Fruit fruit) { }
}
public class Apple : IFruit { }
public class BowlOfApples : BowlOf<Apple> { }
现在,有了它 - 这几乎只是类型的重命名(但将 public interface ChildInterface : BaseInterface {}
更改为 public class Apple : IFruit { }
)然后我们创建了以下问题。
假设我有 public class Banana : IFruit { }
此外,让我们假设以下内容是合法的:
BowlOf<IFruit> c = new BowlOfApples();
然后我可以调用 c.Add(new Banana())
.什么!?! 你不能在一碗苹果中加入一根香蕉。
这就是为什么当您尝试执行 AbstractClass<BaseInterface> c = new ConcreteClass();
时编译器会报错的原因.
关于c# - 为什么继承的接口(interface)不能在通用上下文中转换为其基接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571409/