为什么列表< T>不上协接口MyInterface的&LT有效;出T> [英] Why is List<T> not valid on an covariant interface MyInterface<out T>

查看:130
本文介绍了为什么列表< T>不上协接口MyInterface的&LT有效;出T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

后续问题前一个问题,这已被确定为一个协方的问题。以这一步,如果我修改 IFactory的如下:

Follow up question to a previous question, this has been identified as a co-variance issue. Taking this one step further, if I modify IFactory as follows:

class Program
{
    static void Main(string[] args)
    {
        IFactory<IProduct> factory = new Factory();
    }
}

class Factory : IFactory<Product>
{
}

class Product : IProduct
{
}

interface IFactory<out T> where T : IProduct
{
    List<T> MakeStuff();
}

interface IProduct
{
}

我得到:

无效差异:类型参数T必须是在Sandbox.IFactory.MakeStuff目不暇接有效的()。 T是协变的。

Invalid variance: The type parameter T must be invariantly valid on Sandbox.IFactory.MakeStuff(). T is covariant.

这是为什么不目不暇接有效吗?如何/应该这样解决?

Why is this not invariantly valid? How can/should this be resolved?

推荐答案

@克雷格的回答是正确的。要解决,将其更改为:

@Craig's answer is correct. To resolve, change it to:

IEnumerable<T> MakeStuff()



编辑:至于为什么,看的的IEnumerable< T>接口:

public interface IEnumerable<out T> : IEnumerable



注意的&IList的LT; T>接口没有out关键字。方差支持在接口和委托,而不是类泛型类型参数,所以它并不适用于列出< T>

Note that the IList<T> Interface does not have the out keyword. Variance is supported for generic type parameters in interfaces and delegates, not classes, so it doesn't apply to List<T>.

这篇关于为什么列表&LT; T&GT;不上协接口MyInterface的&LT有效;出T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆