c# - C# : Cannot implicitly convert type 'MyWidget' to 'IWidget' 中的泛型继承

标签 c# generics inheritance

我在使用泛型设置继承时遇到问题。

本质上我想要做的是拥有一个通用接口(interface),它本身接受一个接口(interface)。棘手的部分是“内部”界面可以在其之上分层一个更具体的界面。

这是我尝试构建的结构的代表性示例:

public interface IThing  { }

public interface IMoreSpecificThing : IThing  {  }

public interface IWidget<T> where T : IThing  {  }

public class MySpecificThing : IMoreSpecificThing { }

public class MyWidget : IWidget<MySpecificThing> { }

public class MyClass
{
    public IWidget<IThing> MyProperty { get; set; }

    public MyClass()
    {
        MyProperty = new MyWidget();
    }
}

问题是当我将 MyWidget 分配给 MyProperty 时,我收到以下错误:

Cannot implicitly convert type 'MyWidget' to 'IWidget<IThing>'. An explicit conversion exists (are you missing a cast?)

我做错了什么,有没有办法正确地做到这一点?

最佳答案

这需要使您的界面协变:

public interface IWidget<out T> where T : IThing  {  }

有关详细信息,请参阅 Covariance and Contravariance in Generics .请注意,这确实对接口(interface)施加了限制,主要是:

All the type parameters of these interfaces are covariant, so the type parameters are used only for the return types of the members.

关于c# - C# : Cannot implicitly convert type 'MyWidget' to 'IWidget' 中的泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19100740/

相关文章:

c# - 将具体转换为基础通用抽象类的解决方法

c# - 有没有更好的方法来实现一个可继承的方法,该方法返回一个继承自该类类型的对象?

c# - .net 中的 Xml 序列化和架构 (C#)

c# - ContentControl 的格式泄露到控制之外

java - 为什么泛型绑定(bind) "E implements I"会导致编译器错误?

generics - F# ICastableTo<'T> 等效吗?

c# - struct 与 for 循环的使用

c# - 如何获得枚举数作为常量?

python - 继承 : Base class method which returns an instance of itself

c# - 如果有意隐藏,请使用 new 关键字