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

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

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

sql - Microsoft SQL服务器

compiler-errors - Lazarus IDE-编译失败: Cannot open in

actionscript-3 - for(const i)而不是(var i)

caching - 如何处理并发Web用户的重置CS-Script

android - Android Delphi xe7中的错误