简体   繁体   English

协方差和泛型类型

[英]Covariance and generic types

Why does the following code give a compile error for the generic case? 为什么以下代码为通用案例提供编译错误?

abstract class Test<TItem> where TItem : IFoo
{
    public IEnumerable<IFoo> Foos { get; set; }

    public void Assign()
    {
        Foos = GetSomeSpecificList(); // works as expected
        Foos = GetSomeGenericList(); // compile error?
    }

    protected abstract ICollection<TItem> GetSomeGenericList();

    protected abstract ICollection<Foo> GetSomeSpecificList();
}

interface IFoo
{
}

class Foo : IFoo
{
}

Am I missing something or isn't it given that every TItem must be an IFoo and therefore it's impossible for this construct to violate type safety? 我错过了什么或不是因为每个TItem都必须是IFoo,因此这个结构不可能违反类型安全吗?

You don't have a class constraint, therefore TItem could be a struct type implementing the IFoo interface. 您没有class约束,因此TItem可以是实现IFoo接口的struct类型。 Covariance requires reference types. 协方差需要参考类型。 When you add the class constraint, it compiles without issues. 添加class约束时,它会编译没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM