接口列表与派生类型列表 - 无法将表达式类型转换为返回类型 [英] List of Interfaces vs. List of Derived Type - Cannot Convert Expression Type to Return Type

查看:156
本文介绍了接口列表与派生类型列表 - 无法将表达式类型转换为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

public IList<ICoupon> GetCouponsForSite(string siteSlug)
{
    var coupons = _db.Coupons.Where(x => x.Site.slug == siteSlug)
                     .Select(x => new Coupon(x.id));

    var list = new List<ICoupon>();
    foreach (var coupon in coupons)
    {
        list.Add(coupon);
    }

    return list;
}

但这不起作用(错误 - 无法将表达式转换为返回类型):

But this does does not work (error - cannot convert expression type to return type):

public IList<ICoupon> GetCouponsForSite(string siteSlug)
{
    return _db.Coupons.Where(x => x.Site.slug == siteSlug)
                      .Select(x => new Coupon(x.id)).ToList();
}


推荐答案

因为db.Coupons .. .ToList()返回 IList< Coupon> 而不是 IList< ICoupon> IList<优惠券> 不是来自 IList< ICoupon> ,因为C#3不支持通用差异。 (C#4确实支持通用方差,但在这种情况下它仍然不会得到。考虑到收到 IList< ICoupon> 的人可能会尝试将SomeEvilTypeThatImplementsICoupon填充到其中。但是 IList< Coupon> 无法接受,因为SomeEvilTypeThatImplementsICoupon不是来自优惠券。请参阅 http://hestia.typepad.com/flatlander/2008/12/c-covariance-and-convvariance-by -example.html ,用于讨论此可兑换问题,虽然情况略有不同,并且Eric Lippert文章从那里链接。)

Because db.Coupons...ToList() returns an IList<Coupon> rather than an IList<ICoupon>. IList<Coupon> does not derive from IList<ICoupon> because C# 3 doesn't support generic variance. (C# 4 does support generic variance, but it still won't derive in this case. Consider that whoever receives an IList<ICoupon> could try to stuff a SomeEvilTypeThatImplementsICoupon into it. But an IList<Coupon> couldn't accept that because SomeEvilTypeThatImplementsICoupon doesn't derive from Coupon. See http://hestia.typepad.com/flatlander/2008/12/c-covariance-and-contravariance-by-example.html for discussion of this convertibility issue albeit in a slightly different context, and the Eric Lippert articles linked from there.)

(您的第一个代码段)相反,显式构建一个 List< ICoupon> ,其中可以包含任何实现ICoupon的东西,然后将一些Coupon对象放入该列表中。现在,如果接收者决定将SomeEvilTypeThatImplementsICoupon戳入一切都很好,因为List是为了保存任何ICoupon,而不仅仅是实际的Coupon对象。)

(Your first snippet, by contrast, explicitly constructs a List<ICoupon>, which can contain anything that implements ICoupon, and then puts some Coupon objects into that list. Now if the receiver decides to poke SomeEvilTypeThatImplementsICoupon into it, all is well, because the List was built to hold any ICoupon, not just actual Coupon objects.)

这篇关于接口列表与派生类型列表 - 无法将表达式类型转换为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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