How to Convert IList<SomeObject> to IList<ISomeInterface> where SomeObject implements ISomeInterface using covariance in C# 4.0

℡╲_俬逩灬. 提交于 2019-12-06 11:53:13

why not simply use

IList<Items> GetItems;
IList<IItems> items = GetItems().Cast<IItems>().ToList(); 

For this to work as you are thinking then I believe IList would have to be declared as covariant, not the items in the list. And IList does not support covariance. The only .NET interfaces that were updated to support covariance are:

  • IEnumerable (T is covariant)
  • IEnumerator (T is covariant)
  • IQueryable (T is covariant)
  • IGrouping (TKey and TElement are covariant)
  • IComparer (T is contravariant)
  • IEqualityComparer (T is contravariant)
  • IComparable (T is contravariant)

This from http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

Technically, the following will work, but I don't think this is exactly what you're looking for...

IList<IItems> items = GetItems().ToArray() as IList<IItems>;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!