c# - 如何从 C# 中的封闭构造类中获取基类对象

标签 c# generics inheritance compiler-errors

只是另一个小型 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> .

现在输入 clothICloth<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/

相关文章:

java - 收集器与结果类型中的通配符不匹配

java - 如何使用接口(interface)作为 map 的键

java - Object类怎么可能是子类的父类(super class)呢?

java - 为什么我的多态父类从自身内部调用子类方法?

c# - 如何将表达式 Func<T, object[]> 转换为 Func<T, object>

c# - 在 WCF 项目中放置常量的位置

java - 什么是 PECS(生产者扩展消费者 super )?

python - 使用继承编写 __repr__ 函数的正确方法

c# - 任何好的 SharpNEAT 教程?

c# - 创建具有动态字段的数据库