且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-09-08 07:24:17

假定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.)