只是另一个小型 C# 培训应用程序,只是另一个编译错误,但它不能从我身边消失……我只是想知道,我在这里做错了什么:
public abstract class Material
{
}
public abstract class Cloth<T> where T:Material
{
public T Prop { get; set; }
}
public class Cotton : Material
{
}
public class Dress<T> : Cloth<T> where T : Material
{
}
public class Test
{
private Cloth<Material> cloth;
public Test()
{
/* below won't compile */
cloth = new Dress<Cotton>();
}
}
Cannot implicitly convert type Dress<Cotton> to Cloth<Material>
最佳答案
你想要达到的叫协方差 (see the following article for samples)。
不幸的是,类没有变体支持:它仅限于接口(interface)和委托(delegate)。
因此,或者,您可以设计一个名为 ICloth<T>
的接口(interface)。与 T
协变:
public interface ICloth<out T>
{
T Prop { get; set; }
}
Cloth<T>
.cloth
如ICloth<T>
并且您的作业应该有效(即 cloth = new Dress<Cotton>();
),因为 Dress<Cotton>
是 ICloth<out T>
,这是一个带有 T
的接口(interface)协变泛型参数。https://stackoverflow.com/questions/27890140/
相关文章:
compilation - 如何在Windows上的SCons中导出具有备用扩展名的程序
opencv - 使用 CUDA 支持构建 OpenCV transpose.cu 上的错误
compiler-errors - 如何解决MiniZinc错误: “model inconsist
actionscript-3 - 如果使用 Flash Builder 4.7 而不是 4.6,则基
macos - AudioFileReadPackets错误-50
compiler-errors - Lazarus IDE-编译失败: Cannot open in
actionscript-3 - for(const i)而不是(var i)