我在使用泛型设置继承时遇到问题。
本质上我想要做的是拥有一个通用接口(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/