无法隐式转换类型'System.Collections.Generic.List< >'到"System.Collections.Generic.IList" >'

无法隐式转换类型'System.Collections.Generic.List< >'到

问题描述:

这篇文章可能有很多重复.但是我尝试了其中的大多数,不幸的是我的错误仍然存​​在 发生.

There are lots of possible duplicates for this post.But i tried most of thems, unfortunately my error still happens.

错误为:错误1无法将类型'System.Collections.Generic.List<Report.Business.ViewModels.InvoiceMaster>'隐式转换为'System.Collections.Generic.IList<ICSNew.Data.InvoiceHD>'.存在显式转换(您是否缺少演员表?)

Error is : Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<Report.Business.ViewModels.InvoiceMaster>' to 'System.Collections.Generic.IList<ICSNew.Data.InvoiceHD>'. An explicit conversion exists (are you missing a cast?)

public IList<InvoiceHD> GetAllInvoiceMasterDetailsByInvoiceId(int InvoiceId)
{
    var dbMstDtl = ireportrepository.GetAllInvoiceMasterDetailsByInvoiceId(InvoiceId);

    var MstDtl = from mst in dbMstDtl 
                 select new Report.Business.ViewModels.InvoiceMaster 
                 {
                     ModifiedDate = mst.ModifiedDate,
                     SubTotal = Convert.ToDecimal(mst.SubTotal),
                     TotalDiscount = Convert.ToDecimal(mst.TotalDiscount),
                     VAT = Convert.ToDecimal(mst.VAT),
                     NBT = Convert.ToDecimal(mst.NBT),
                     AmtAfterDiscount = Convert.ToDecimal(mst.AmtAfterDiscount)
                 };

    return MstDtl.ToList();
}

在某些帖子中,我看到他们使用 return MstDtl.AsEnumerable().ToList();

In some post i saw this thing solved when they use return MstDtl.AsEnumerable().ToList();

但就我而言,它也不起作用(出现错误)

But in my case it also not working(getting errors)

假定InvoiceMaster源自或实现InvoiceHD,并且您使用的是C#4和.NET 4或更高版本,则可以只使用通用方差:

Assuming InvoiceMaster derives from or implements InvoiceHD, and that you're using C# 4 and .NET 4 or higher, you can just use generic variance:

return MstDtl.ToList<InvoiceHD>();

这利用了IEnumerable<InvoiceMaster>IEnumerable<InvoiceHD>的事实,因为IEnumerable<T>T中是协变变量.

This uses the fact that an IEnumerable<InvoiceMaster> is an IEnumerable<InvoiceHD> because IEnumerable<T> is covariant in T.

另一种解决方法是将MstDtl的声明更改为使用显式键入:

Another way to solve it would be to change the declaration of MstDtl to use explicit typing:

IEnumerable<InvoiceMaster> MstDtl = ...;

(我还建议遵循常规C#命名,其中局部变量以小写字母开头,但这是另一回事.)

(I'd also suggest following regular C# naming, where local variables start with a lower-case letter, but that's a different matter.)