c# - 为什么继承的接口(interface)不能在通用上下文中转换为其基接口(interface)?

标签 c#

我试图在我的 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/

相关文章:

c# - Wix 安装程序 : Error when tring to run a custom action from a button click - A DLL required for this install to complete could not be run

c# - 在 Gtk# 中,如何在拖放中传递对象引用?

c# - Visual Studio 中的 “Go To Definition” 仅显示非项目引用的元数据

c# - 在代码隐藏中访问无序列表控件 ID

c# - 这样的集合是否存在(Dictionary 和 HashSet 的功能)?

c# - 在 C# 中将字符串拆分为特定格式?

c# - 页面方法和安全

c# - 如何使用 ObservableCollection 从 ViewModel 刷新 UI?

c# - 是否有在 Dapper 中为 QueryFirstAsync 或 QueryFirstOrDefaultAsync 进行多重映射的选项?

c# - double[] 集合到字符串