只是另一个小型 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)协变泛型参数。了解更多关于具有差异的通用接口(interface) in the following article on MSDN .
关于c# - 如何从 C# 中的封闭构造类中获取基类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890140/